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.25;
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != owner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title -Name Filter- v0.1.9
*/
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* Math operations with safety checks
*/
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract CelebrityGame is Ownable {
using SafeMath for *;
using NameFilter for string;
string constant public gameName = "Celebrity Game";
// fired whenever a card is created
event LogNewCard(string name, uint256 id);
// fired whenever a player is registered
event LogNewPlayer(string name, uint256 id);
//just for isStartEnable modifier
bool private isStart = false;
uint256 private roundId = 0;
struct Card {
bytes32 name; // card owner name
uint256 fame; // The number of times CARDS were liked
uint256 fameValue; // The charge for the current card to be liked once
uint256 notorious; // The number of times CARDS were disliked
uint256 notoriousValue; // The charge for the current card to be disliked once
}
struct CardForPlayer {
uint256 likeCount; // The number of times the player likes it
uint256 dislikeCount; // The number of times the player disliked it
}
struct CardWinner {
bytes32 likeWinner;
bytes32 dislikeWinner;
}
Card[] public cards;
bytes32[] public players;
mapping (uint256 => mapping (uint256 => mapping ( uint256 => CardForPlayer))) public playerCard; // returns cards of this player like or dislike by playerId and roundId and cardId
mapping (uint256 => mapping (uint256 => CardWinner)) public cardWinnerMap; // (roundId => (cardId => winner)) returns winner by roundId and cardId
mapping (uint256 => Card[]) public rounCardMap; // returns Card info by roundId
mapping (bytes32 => uint256) private plyNameXId; // (playerName => Id) returns playerId by playerName
mapping (bytes32 => uint256) private cardNameXId; // (cardName => Id) returns cardId by cardName
mapping (bytes32 => bool) private cardIsReg; // (cardName => cardCount) returns cardCount by cardName,just for createCard function
mapping (bytes32 => bool) private playerIsReg; // (playerName => isRegister) returns registerInfo by playerName, just for registerPlayer funciton
mapping (uint256 => bool) private cardIdIsReg; // (cardId => card info) returns card info by cardId
mapping (uint256 => bool) private playerIdIsReg; // (playerId => id) returns player index of players by playerId
mapping (uint256 => uint256) private cardIdXSeq;
mapping (uint256 => uint256) private playerIdXSeq;
/**
* @dev used to make sure no one can interact with contract until it has been started
*/
modifier isStartEnable {
require(isStart == true);
_;
}
/**
* the contract precision is 1000
*/
constructor() public {
string[8] memory names= ["SatoshiNakamoto","CZ","HeYi","LiXiaolai","GuoHongcai","VitalikButerin","StarXu","ByteMaster"];
uint256[8] memory _ids = [uint256(183946248739),536269148721,762415028463,432184367532,398234673241,264398721023,464325189620,217546321806];
for (uint i = 0; i < 8; i++){
string memory _nameString = names[i];
uint256 _id = _ids[i];
bytes32 _name = _nameString.nameFilter();
require(cardIsReg[_name] == false);
uint256 _seq = cards.push(Card(_name, 1, 1000, 1, 1000)) - 1;
cardIdXSeq[_id] = _seq;
cardNameXId[_name] = _id;
cardIsReg[_name] = true;
cardIdIsReg[_id] = true;
}
}
/**
* @dev use this function to create card.
* - must pay some create fees.
* - name must be unique
* - max length of 32 characters long
* @param _nameString owner desired name for card
* @param _id card id
* (this might cost a lot of gas)
*/
function createCard(string _nameString, uint256 _id) public onlyOwner() {
require(keccak256(abi.encodePacked(_name)) != keccak256(abi.encodePacked("")));
bytes32 _name = _nameString.nameFilter();
require(cardIsReg[_name] == false);
uint256 _seq = cards.push(Card(_name, 1, 1000, 1, 1000)) - 1;
cardIdXSeq[_id] = _seq;
cardNameXId[_name] = _id;
cardIsReg[_name] = true;
cardIdIsReg[_id] = true;
emit LogNewCard(_nameString, _id);
}
/**
* @dev use this function to register player.
* - must pay some register fees.
* - name must be unique
* - name cannot be null
* - max length of 32 characters long
* @param _nameString team desired name for player
* @param _id player id
* (this might cost a lot of gas)
*/
function registerPlayer(string _nameString, uint256 _id) external {
require(keccak256(abi.encodePacked(_name)) != keccak256(abi.encodePacked("")));
bytes32 _name = _nameString.nameFilter();
require(playerIsReg[_name] == false);
uint256 _seq = players.push(_name) - 1;
playerIdXSeq[_id] = _seq;
plyNameXId[_name] = _id;
playerIsReg[_name] = true;
playerIdIsReg[_id] = true;
emit LogNewPlayer(_nameString, _id);
}
/**
* @dev this function for One player likes the CARD once.
* @param _cardId must be returned when creating CARD
* @param _playerId must be returned when registering player
* (this might cost a lot of gas)
*/
function likeCelebrity(uint256 _cardId, uint256 _playerId) external isStartEnable {
require(cardIdIsReg[_cardId] == true, "sorry create this card first");
require(playerIdIsReg[_playerId] == true, "sorry register the player name first");
Card storage queryCard = cards[cardIdXSeq[_cardId]];
queryCard.fame = queryCard.fame.add(1);
queryCard.fameValue = queryCard.fameValue.add(queryCard.fameValue / 100*1000);
playerCard[_playerId][roundId][_cardId].likeCount == (playerCard[_playerId][roundId][_cardId].likeCount).add(1);
cardWinnerMap[roundId][_cardId].likeWinner = players[playerIdXSeq[_playerId]];
}
/**
* @dev this function for One player dislikes the CARD once.
* @param _cardId must be returned when creating CARD
* @param _playerId must be created when registering player
* (this might cost a lot of gas)
*/
function dislikeCelebrity(uint256 _cardId, uint256 _playerId) external isStartEnable {
require(cardIdIsReg[_cardId] == true, "sorry create this card first");
require(playerIdIsReg[_playerId] == true, "sorry register the player name first");
Card storage queryCard = cards[cardIdXSeq[_cardId]];
queryCard.notorious = queryCard.notorious.add(1);
queryCard.notoriousValue = queryCard.notoriousValue.add(queryCard.notoriousValue / 100*1000);
playerCard[_playerId][roundId][_cardId].dislikeCount == (playerCard[_playerId][roundId][_cardId].dislikeCount).add(1);
cardWinnerMap[roundId][_cardId].dislikeWinner = players[playerIdXSeq[_playerId]];
}
/**
* @dev use this function to reset card properties.
* - must be called when game is not started by team.
* @param _id must be returned when creating CARD
* (this might cost a lot of gas)
*/
function reset(uint256 _id) external onlyOwner() {
require(isStart == false);
Card storage queryCard = cards[cardIdXSeq[_id]];
queryCard.fame = 1;
queryCard.fameValue = 1000;
queryCard.notorious = 1;
queryCard.notoriousValue = 1000;
}
/**
* @dev use this function to start the game.
* - must be called by owner.
* (this might cost a lot of gas)
*/
function gameStart() external onlyOwner() {
isStart = true;
roundId = roundId.add(1);
}
/**
* @dev use this function to end the game. Just for emergency control by owner
* (this might cost a lot of gas)
*/
function gameEnd() external onlyOwner() {
isStart = false;
rounCardMap[roundId] = cards;
}
/**
* @dev use this function to get CARDS count
* @return Total all CARDS in the current game
*/
function getCardsCount() public view returns(uint256) {
return cards.length;
}
/**
* @dev use this function to get CARDS id by its name.
* @param _nameString must be created when creating CARD
* @return the card id
*/
function getCardId(string _nameString) public view returns(uint256) {
bytes32 _name = _nameString.nameFilter();
require(cardIsReg[_name] == true, "sorry create this card first");
return cardNameXId[_name];
}
/**
* @dev use this function to get player id by the name.
* @param _nameString must be created when creating CARD
* @return the player id
*/
function getPlayerId(string _nameString) public view returns(uint256) {
bytes32 _name = _nameString.nameFilter();
require(playerIsReg[_name] == true, "sorry register the player name first");
return plyNameXId[_name];
}
/**
* @dev use this function to get player bet count.
* @param _playerName must be created when registering player
* @param _roundId must be a game that has already started
* @param _cardName the player id must be created when creating CARD
* @return likeCount
* @return dislikeCount
*/
function getPlayerBetCount(string _playerName, uint256 _roundId, string _cardName) public view returns(uint256 likeCount, uint256 dislikeCount) {
bytes32 _cardNameByte = _cardName.nameFilter();
require(cardIsReg[_cardNameByte] == false);
bytes32 _playerNameByte = _playerName.nameFilter();
require(playerIsReg[_playerNameByte] == false);
return (playerCard[plyNameXId[_playerNameByte]][_roundId][cardNameXId[_cardNameByte]].likeCount, playerCard[plyNameXId[_playerNameByte]][_roundId][cardNameXId[_cardNameByte]].dislikeCount);
}
} | (roundId => (cardId => winner)) returns winner by roundId and cardId
| mapping (uint256 => mapping (uint256 => CardWinner)) public cardWinnerMap; | 12,614,165 | [
1,
12,
2260,
548,
516,
261,
3327,
548,
516,
5657,
1224,
3719,
1135,
5657,
1224,
635,
3643,
548,
471,
5270,
548,
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,
2874,
261,
11890,
5034,
516,
2874,
261,
11890,
5034,
516,
14338,
59,
7872,
3719,
1071,
5270,
59,
7872,
863,
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
]
|
pragma solidity ^0.4.24;
// ----------------------------------------------------------------------------
// SPEC token contract
//
// Deployed to : 0x0BE562139564fd244FD523449f196f47Df26b420
// Symbol : SPEC
// Name : Spectrium
// Total supply: 1500000000
// Decimals : 18
//
// Enjoy.
//
// (c) by Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
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;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract Spectrium is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
constructor() public {
symbol = "SPEC";
name = "Spectrium";
decimals = 18;
_totalSupply = 1500000000000000000000000000;
balances[0x0BE562139564fd244FD523449f196f47Df26b420] = _totalSupply;
emit Transfer(address(0), 0x0BE562139564fd244FD523449f196f47Df26b420, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account tokenOwner
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to to account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
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;
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer tokens from the from account to the to account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the from account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, 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;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for spender to transferFrom(...) tokens
// from the token owner's account. The spender contract function
// receiveApproval(...) is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable {
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract Spectrium is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
constructor() public {
symbol = "SPEC";
name = "Spectrium";
decimals = 18;
_totalSupply = 1500000000000000000000000000;
balances[0x0BE562139564fd244FD523449f196f47Df26b420] = _totalSupply;
emit Transfer(address(0), 0x0BE562139564fd244FD523449f196f47Df26b420, _totalSupply);
}
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
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 approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, 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;
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
function () public payable {
revert();
}
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
} | 15,424,915 | [
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
8879,
17082,
11417,
8879,
17082,
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
]
| [
1,
1,
1,
1,
1,
1,
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
]
| [
1,
16351,
348,
1181,
566,
379,
353,
4232,
39,
3462,
1358,
16,
14223,
11748,
16,
14060,
10477,
288,
203,
565,
533,
1071,
3273,
31,
203,
565,
533,
1071,
225,
508,
31,
203,
565,
2254,
28,
1071,
15105,
31,
203,
565,
2254,
1071,
389,
4963,
3088,
1283,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
3719,
2935,
31,
203,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
3273,
273,
315,
13847,
14432,
203,
3639,
508,
273,
315,
55,
1181,
566,
379,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
4711,
12648,
12648,
2787,
9449,
31,
203,
3639,
324,
26488,
63,
20,
92,
20,
5948,
4313,
22,
3437,
8778,
1105,
8313,
3247,
24,
16894,
25,
4366,
6334,
29,
74,
28644,
74,
9462,
40,
74,
5558,
70,
24,
3462,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
374,
92,
20,
5948,
4313,
22,
3437,
8778,
1105,
8313,
3247,
24,
16894,
25,
4366,
6334,
29,
74,
28644,
74,
9462,
40,
74,
5558,
70,
24,
3462,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
225,
300,
324,
26488,
63,
2867,
12,
20,
13,
15533,
203,
565,
289,
203,
203,
203,
565,
445,
11013,
951,
12,
2867,
1147,
5541,
13,
1071,
5381,
1135,
261,
11890,
11013,
2
]
|
./full_match/1/0xC4c743bf0f5F0fac100BCB6cdBd5Bdca3ad3Cd75/sources/contracts/ApemoArmyOperator.sol | Sets the merkle roots for the allow lists | function setAllowListMerkleRoot(AllowLists allowList, bytes32 merkleRoot)
external
onlyOperator
{
allowListMerkleRoots[allowList] = merkleRoot;
}
| 3,087,850 | [
1,
2785,
326,
30235,
12876,
364,
326,
1699,
6035,
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,
7009,
682,
8478,
15609,
2375,
12,
7009,
7432,
1699,
682,
16,
1731,
1578,
30235,
2375,
13,
203,
3639,
3903,
203,
3639,
1338,
5592,
203,
565,
288,
203,
3639,
1699,
682,
8478,
15609,
17540,
63,
5965,
682,
65,
273,
30235,
2375,
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
]
|
./full_match/1/0x15480f5B5ED98A94e1d36b52Dd20e9a35453A38e/sources/contracts/mixins/Auth.sol | checks: caller has PAUSER effects: tradingPaused' = false | function unpauseTrading() external onlyRole(PAUSER) {
emit TradingPausedSet(tradingPaused, false);
tradingPaused = false;
}
| 4,999,847 | [
1,
12366,
30,
4894,
711,
15662,
4714,
16605,
30,
1284,
7459,
28590,
11,
273,
629,
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,
445,
640,
19476,
1609,
7459,
1435,
3903,
1338,
2996,
12,
4066,
4714,
13,
288,
203,
3639,
3626,
2197,
7459,
28590,
694,
12,
313,
14968,
28590,
16,
629,
1769,
203,
3639,
1284,
7459,
28590,
273,
629,
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
]
|
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
| event BURN595(address indexed burner, uint256 value); | 6,431,936 | [
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,
225,
871,
605,
8521,
6162,
25,
12,
2867,
8808,
18305,
264,
16,
2254,
5034,
460,
1769,
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,
-100,
-100,
-100,
-100
]
|
// 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);
}
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
/**
* @dev Implementation of the Storage Fleet Token.
*/
contract FLTToken is ERC20 {
constructor() ERC20("FleetToken", "FLT") {
_mint(msg.sender, 1200000000000000000000000000);
}
} | @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./ | contract Context {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| 1,199,331 | [
1,
17727,
1779,
2973,
326,
783,
4588,
819,
16,
6508,
326,
5793,
434,
326,
2492,
471,
2097,
501,
18,
21572,
4259,
854,
19190,
2319,
3970,
1234,
18,
15330,
471,
1234,
18,
892,
16,
2898,
1410,
486,
506,
15539,
316,
4123,
279,
2657,
21296,
16,
3241,
1347,
21964,
598,
2191,
17,
20376,
326,
2236,
5431,
471,
8843,
310,
364,
4588,
2026,
486,
506,
326,
3214,
5793,
261,
345,
10247,
487,
392,
2521,
353,
356,
2750,
11748,
2934,
1220,
6835,
353,
1338,
1931,
364,
12110,
16,
5313,
17,
5625,
20092,
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,
16351,
1772,
288,
203,
97,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3576,
751,
1435,
2713,
1476,
5024,
1135,
261,
3890,
745,
892,
13,
288,
203,
3639,
327,
1234,
18,
892,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xe8434EfD177CC29B8550963F5C066Fd2F7d623f9/sources/BARA.sol | Preloaded tokens are sold out Spiral auto lp concept, transfer tokens directly to the Pair | function swapBack() private {
uint256 contractBalance;
if (taxfree) {
if (_tokenstoswap > balanceOf(address(this))) {
_tokensForLiquidity = 0;
contractBalance = balanceOf(address(this));
taxfree = false;
TaxFee = 0;
TotalFees = 0;
contractBalance = _tokensForTax;
}
contractBalance = balanceOf(address(this));
}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
if (_tokensForLiquidity > 0) {
super._transfer(address(this), uniswapV2Pair, _tokensForLiquidity);
if (!taxfree) {
contractBalance = contractBalance.sub(_tokensForLiquidity);
}
}
swapTokensForEth(contractBalance);
_tokensForTax = 0;
_tokensForLiquidity = 0;
_tokenstoswap = 0;
}
| 2,619,345 | [
1,
1386,
4230,
2430,
854,
272,
1673,
596,
5878,
481,
287,
3656,
12423,
12402,
16,
7412,
2430,
5122,
358,
326,
8599,
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,
7720,
2711,
1435,
3238,
288,
203,
3639,
2254,
5034,
6835,
13937,
31,
203,
540,
203,
3639,
309,
261,
8066,
9156,
13,
288,
203,
5411,
309,
261,
67,
2316,
334,
538,
91,
438,
405,
11013,
951,
12,
2867,
12,
2211,
20349,
288,
203,
7734,
389,
7860,
1290,
48,
18988,
24237,
273,
374,
31,
203,
7734,
6835,
13937,
273,
11013,
951,
12,
2867,
12,
2211,
10019,
203,
7734,
5320,
9156,
273,
629,
31,
203,
7734,
18240,
14667,
273,
374,
31,
203,
7734,
10710,
2954,
281,
273,
374,
31,
203,
7734,
6835,
13937,
273,
389,
7860,
1290,
7731,
31,
203,
5411,
289,
203,
5411,
6835,
13937,
273,
11013,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
289,
203,
203,
7010,
7010,
3639,
309,
12,
16351,
13937,
405,
7720,
5157,
861,
6275,
380,
4200,
15329,
203,
6647,
6835,
13937,
273,
7720,
5157,
861,
6275,
380,
4200,
31,
203,
1850,
289,
203,
377,
203,
3639,
309,
261,
67,
7860,
1290,
48,
18988,
24237,
405,
374,
13,
288,
203,
5411,
2240,
6315,
13866,
12,
2867,
12,
2211,
3631,
640,
291,
91,
438,
58,
22,
4154,
16,
389,
7860,
1290,
48,
18988,
24237,
1769,
203,
5411,
309,
16051,
8066,
9156,
13,
288,
203,
7734,
6835,
13937,
273,
6835,
13937,
18,
1717,
24899,
7860,
1290,
48,
18988,
24237,
1769,
203,
5411,
289,
203,
3639,
289,
203,
540,
203,
3639,
7720,
5157,
1290,
41,
451,
12,
16351,
13937,
1769,
203,
203,
3639,
389,
7860,
1290,
7731,
273,
374,
31,
203,
3639,
389,
7860,
1290,
48,
18988,
24237,
273,
374,
31,
203,
2
]
|
pragma solidity ^0.4.15;
contract AccessRights {
uint constant MAX_GUARDIANSHIP = 20;
uint constant MAX_FUNC_LIST = 50;
struct ContractStruct{
string Name;
uint Guardianship;
address NewAddress;
bool WriteValid;
bool GlobalReadValid;
uint State;
uint [MAX_GUARDIANSHIP] SubGuardianshipList;
address [MAX_FUNC_LIST] FunctionList;
uint [MAX_FUNC_LIST] AccessGroupList;
}
mapping (address => ContractStruct) ContractTable;
struct GuardianshipStruct{
string Name;
address [2] GuardianList;
address [] ContractList;
address [] ContributorList;
address AddVote;
address RemoveVote;
}
GuardianshipStruct [MAX_GUARDIANSHIP] GuardianshipTable;
struct ContributorStruct{
string Name;
uint Guardianship;
uint Limit;
uint AccessGroup;
uint LastBlockNumber;
}
mapping (address => ContributorStruct) ContributorTable;
function InitGuardianship() public
{
if (GuardianshipTable[1].GuardianList[0] == 0)
GuardianshipTable[1].GuardianList[0] = msg.sender;
return;
}
function WriteContractFunctionIndex(address Contract, uint FunctionIndex, address FunctionAddress, uint AccessGroup) public
{
bool Match;
uint Index;
(Match, Index) = GuardianshipIndex(msg.sender);
if (!Match)
return;
if (ContractTable[Contract].Guardianship != Index)
return;
ContractTable[Contract].FunctionList[FunctionIndex] = FunctionAddress;
ContractTable[Contract].AccessGroupList[FunctionIndex] = AccessGroup;
}
function ReadContractFunctionIndex(address Contract, uint FunctionIndex) public constant returns (address FunctionAddress, uint AccessGroup)
{
FunctionAddress = ContractTable[Contract].FunctionList[FunctionIndex];
AccessGroup = ContractTable[Contract].AccessGroupList[FunctionIndex];
return;
}
function ReadContractFunctionAccessGroup(address Contract, address FunctionAddress) public constant returns (bool Match, uint AccessGroup)
{
uint Loop;
Match = false;
AccessGroup = 0xFFFFFFFF;
Loop = 0;
while (Loop < MAX_FUNC_LIST)
{
if (ContractTable[Contract].FunctionList[Loop] == 0)
return;
if (ContractTable[Contract].FunctionList[Loop] == FunctionAddress)
{
AccessGroup = ContractTable[Contract].AccessGroupList[Loop];
Match = true;
return;
}
Loop = Loop + 1;
}
}
function WriteGuardianshipName (string Name) public
{
bool Match;
uint Index;
(Match, Index) = GuardianshipIndex(msg.sender);
if (!Match)
return;
GuardianshipTable[Index].Name = Name;
}
function ReadGuardianshipContributor(address GuardianAddress, uint ListIndex) public constant returns (address RetContributorAddress)
{
bool Match;
uint Index;
(Match, Index) = GuardianshipIndex(GuardianAddress);
if (!Match)
return;
RetContributorAddress = GuardianshipTable[Index].ContributorList[ListIndex];
return;
}
function ReadGuardianshipContract(address GuardianAddress, uint ListIndex) public constant returns (address RetContractAddress)
{
bool Match;
uint Index;
(Match, Index) = GuardianshipIndex(GuardianAddress);
if (!Match)
return;
RetContractAddress = GuardianshipTable[Index].ContractList[ListIndex];
return;
}
function ReadGuardianship(address GuardianAddress) public constant returns (
bool Match,
uint GIndex,
address GuardianA,
address GuardianB,
string Name,
uint ContractListLength,
uint ContributorListLength,
address AddVote,
address RemoveVote)
{
Name = "NULL";
ContractListLength = 0;
ContributorListLength = 0;
AddVote = 0;
RemoveVote = 0;
uint Index;
(Match, Index) = GuardianshipIndex(GuardianAddress);
if (!Match)
return;
GIndex = Index;
GuardianA = GuardianshipTable[Index].GuardianList[0];
GuardianB = GuardianshipTable[Index].GuardianList[1];
Name = GuardianshipTable[Index].Name;
ContractListLength = GuardianshipTable[Index].ContractList.length;
ContributorListLength = GuardianshipTable[Index].ContributorList.length;
AddVote = GuardianshipTable[Index].AddVote;
RemoveVote = GuardianshipTable[Index].RemoveVote;
return;
}
function ReadGuardianshipIndex(uint Index) public constant returns (
address GuardianA,
address GuardianB,
string Name,
uint ContractListLength,
uint ContributorListLength,
address AddVote,
address RemoveVote)
{
GuardianA = GuardianshipTable[Index].GuardianList[0];
GuardianB = GuardianshipTable[Index].GuardianList[1];
Name = GuardianshipTable[Index].Name;
ContractListLength = GuardianshipTable[Index].ContractList.length;
ContributorListLength = GuardianshipTable[Index].ContributorList.length;
AddVote = GuardianshipTable[Index].AddVote;
RemoveVote = GuardianshipTable[Index].RemoveVote;
return;
}
function WriteContractInfo(address ContractAddress, string Name, address NewAddress, bool WriteValid, bool GlobalReadValid, uint State) public
{
bool Match;
uint Index;
(Match, Index) = GuardianshipIndex(msg.sender);
if (!Match)
return;
if (ContractTable[ContractAddress].Guardianship != Index)
return;
ContractTable[ContractAddress].Name = Name;
ContractTable[ContractAddress].NewAddress = NewAddress;
ContractTable[ContractAddress].WriteValid = WriteValid;
ContractTable[ContractAddress].GlobalReadValid = GlobalReadValid;
ContractTable[ContractAddress].State = State;
}
function WriteContractSubGuardianship(address ContractAddress, address SubGuardianId, uint Index) public
{
bool Match;
uint GIndex;
(Match, GIndex) = GuardianshipIndex(msg.sender);
if (!Match)
return;
if (ContractTable[ContractAddress].Guardianship != GIndex)
return;
(Match, GIndex) = GuardianshipIndex(SubGuardianId);
if (!Match)
return;
ContractTable[ContractAddress].SubGuardianshipList[Index] = GIndex;
return;
}
function ReadContractSubGuardianship(address ContractAddress, uint Index) public constant returns (uint SubGuardianship)
{
SubGuardianship = ContractTable[ContractAddress].SubGuardianshipList[Index];
return;
}
function ReadContractInfo(address ContractAddress) public constant returns (
uint Guardianship,
string Name,
address NewAddress,
bool WriteValid,
bool GlobalReadValid,
uint State)
{
Guardianship = ContractTable[ContractAddress].Guardianship;
Name = ContractTable[ContractAddress].Name;
NewAddress = ContractTable[ContractAddress].NewAddress;
WriteValid = ContractTable[ContractAddress].WriteValid;
GlobalReadValid = ContractTable[ContractAddress].GlobalReadValid;
State = ContractTable[ContractAddress].State;
return;
}
function GuardianshipIndex (address GuardianAddress) public constant returns (bool Match, uint Index)
{
Match = false;
Index = 0;
for (uint Loop = 1; Loop < MAX_GUARDIANSHIP; Loop ++)
{
// If the address is 0, then we are looking for an empty slot in which case both addresses
// need to be empty
if (GuardianAddress == 0)
{
if ((GuardianshipTable[Loop].GuardianList[0] == GuardianAddress) && (GuardianshipTable[Loop].GuardianList[1] == GuardianAddress))
{
Match = true;
Index = Loop;
return;
}
}
else
{
if ((GuardianshipTable[Loop].GuardianList[0] == GuardianAddress) || (GuardianshipTable[Loop].GuardianList[1] == GuardianAddress))
{
Match = true;
Index = Loop;
return;
}
}
}
return;
}
function WriteGuardian(address NewGuardianAddress) public
{
bool Match;
uint Index;
(Match, Index) = GuardianshipIndex(msg.sender);
if (!Match)
return;
if (GuardianshipTable[Index].GuardianList[0] == msg.sender)
GuardianshipTable[Index].GuardianList[1] = NewGuardianAddress;
if (GuardianshipTable[Index].GuardianList[1] == msg.sender)
GuardianshipTable[Index].GuardianList[0] = NewGuardianAddress;
}
function CreateContract(address ContractAddress) public
{
bool Match;
uint Index;
(Match, Index) = GuardianshipIndex(msg.sender);
if (!Match)
return;
// Exit if the Contract is already managed by another guardian
if ((ContractTable[ContractAddress].Guardianship != 0) && (ContractTable[ContractAddress].Guardianship != Index))
return;
// Check if the Contract already exsist in the Guardian's Contrct list
for (uint Loop = 0; Loop < GuardianshipTable[Index].ContractList.length; Loop ++)
{
if (GuardianshipTable[Index].ContractList[Loop] == ContractAddress)
return;
}
// Add Contract to Gaurdian's User List
GuardianshipTable[Index].ContractList.push(ContractAddress);
// Init Contract Table
ContractTable[ContractAddress].Guardianship = Index;
ContractTable[ContractAddress].Name = "";
ContractTable[ContractAddress].NewAddress = 0;
ContractTable[ContractAddress].WriteValid = true;
ContractTable[ContractAddress].GlobalReadValid = true;
ContractTable[ContractAddress].State = 1;
return;
}
function CreateContributor(address ContributorAddress, string Name, uint Limit, uint AccessGroup) public
{
bool Match;
uint Index;
(Match, Index) = GuardianshipIndex(msg.sender);
if (!Match)
return;
// Exit if the user is already managed by another guardian
if ((ContributorTable[ContributorAddress].Guardianship != 0) && (ContributorTable[ContributorAddress].Guardianship != Index))
return;
// Check if the user already exsist in the Guardian's user list
for (uint Loop = 0; Loop < GuardianshipTable[Index].ContributorList.length; Loop ++)
{
if (GuardianshipTable[Index].ContributorList[Loop] == ContributorAddress)
return;
}
// Add user to Gaurdian's User List
GuardianshipTable[Index].ContributorList.push(ContributorAddress);
// Init User Table
ContributorTable[ContributorAddress].Name = Name;
ContributorTable[ContributorAddress].Limit = Limit;
ContributorTable[ContributorAddress].Guardianship = Index;
ContributorTable[ContributorAddress].AccessGroup = AccessGroup;
return;
}
function WriteContributor(address ContributorAddress, string Name, uint Limit, uint AccessGroup) public
{
bool Match;
uint Index;
(Match, Index) = GuardianshipIndex(msg.sender);
if (!Match)
return;
if (ContributorTable[ContributorAddress].Guardianship != Index)
return;
ContributorTable[ContributorAddress].Name = Name;
ContributorTable[ContributorAddress].Limit = Limit;
ContributorTable[ContributorAddress].LastBlockNumber = block.number;
ContributorTable[ContributorAddress].AccessGroup = AccessGroup;
return;
}
function ReadContributor(address ContributorAddress) public constant returns (
uint Guardianship,
string Name,
uint Limit,
uint LastBlockNumber,
uint AccessGroup)
{
Guardianship = ContributorTable[ContributorAddress].Guardianship;
Name = ContributorTable[ContributorAddress].Name;
Limit = ContributorTable[ContributorAddress].Limit;
LastBlockNumber = ContributorTable[ContributorAddress].LastBlockNumber;
AccessGroup = ContributorTable[ContributorAddress].AccessGroup;
return;
}
function DeleteContributor(address ContributorAddress) public
{
bool Match;
uint Index;
(Match, Index) = GuardianshipIndex(msg.sender);
if (!Match)
return;
if ((ContributorTable[ContributorAddress].Guardianship != 0) && (ContributorTable[ContributorAddress].Guardianship != Index))
return;
for (uint Loop = 0; Loop < GuardianshipTable[Index].ContributorList.length; Loop ++)
{
if (GuardianshipTable[Index].ContributorList[Loop] == ContributorAddress)
{
GuardianshipTable[Index].ContributorList[Loop] = 0;
ContributorTable[ContributorAddress].Name = "";
ContributorTable[ContributorAddress].Limit = 0;
ContributorTable[ContributorAddress].Guardianship = 0;
ContributorTable[ContributorAddress].LastBlockNumber = 0;
ContributorTable[ContributorAddress].AccessGroup = 0;
return;
}
}
return;
}
function VerifyContractSubGuardianshipList(address ContractId, uint Guardianship) public constant returns (bool Match)
{
Match = false;
// If the Requested Guardianship is 0 then return invalid
if (Guardianship == 0)
return;
// If the contract has no Guadian, then the subGuardianList is invalid
if ((GuardianshipTable[ContractTable[ContractId].Guardianship].GuardianList[0] == 0) &&
(GuardianshipTable[ContractTable[ContractId].Guardianship].GuardianList[1] == 0))
return;
if (ContractTable[ContractId].Guardianship == Guardianship)
{
Match = true;
return;
}
for (uint Loop = 0; Loop < MAX_GUARDIANSHIP; Loop++)
{
if (ContractTable[ContractId].SubGuardianshipList[Loop] == Guardianship)
{
Match = true;
return;
}
}
return;
}
function VerifyContractAccess(address ContractId, address FunctionAddress) public constant returns (bool ReadApproved, bool WriteApproved)
{
bool Match;
uint AccessGroup;
ReadApproved = false;
WriteApproved = false;
// Block all access to unowned contracts
if ((GuardianshipTable[ContractTable[ContractId].Guardianship].GuardianList[0] == 0) &&
(GuardianshipTable[ContractTable[ContractId].Guardianship].GuardianList[1] == 0))
return;
(Match, AccessGroup) = ReadContractFunctionAccessGroup(ContractId, FunctionAddress);
if (Match && ((AccessGroup & ContributorTable[msg.sender].AccessGroup) == 0))
return;
// If GlobalRead approved, then the guardian check is not needed
ReadApproved = ContractTable[ContractId].GlobalReadValid;
// If the user has the same guardian as the contract (or subguardian)
// then ReadApproved = Contract.ReadValid
// Then WriteApproved = Contract.WriteValid only if under the user limit
if (VerifyContractSubGuardianshipList(ContractId, ContributorTable[msg.sender].Guardianship))
{
if (ContractTable[ContractId].GlobalReadValid)
ReadApproved = true;
if (ContributorTable[msg.sender].Limit > 0)
{
// Verify that the user has not exceed their rate limit
if ((ContributorTable[msg.sender].LastBlockNumber + ContributorTable[msg.sender].Limit) > block.number)
WriteApproved = false;
else
WriteApproved = ContractTable[ContractId].WriteValid;
}
else
WriteApproved = ContractTable[ContractId].WriteValid;
}
return;
}
function UpdateContributorBlock() public
{
ContributorTable[msg.sender].LastBlockNumber = block.number;
return;
}
function GuardianshipVoteStats(address NewGuardian) public constant returns (uint AddAgreeCount, uint AddDisagreeCount, uint RemoveAgreeCount, uint RemoveDisagreeCount)
{
uint Loop = 1;
AddAgreeCount = 0;
AddDisagreeCount = 0;
RemoveAgreeCount = 0;
RemoveDisagreeCount = 0;
while (Loop < MAX_GUARDIANSHIP)
{
// Make sure the ContractAdmin is a valid ID when counting votes
if ((GuardianshipTable[Loop].GuardianList[0] != 0) || (GuardianshipTable[Loop].GuardianList[1] != 0))
{
// Update Add
if (GuardianshipTable[Loop].AddVote == NewGuardian)
AddAgreeCount = AddAgreeCount + 1;
else
AddDisagreeCount = AddDisagreeCount + 1;
// Update Remove
if (GuardianshipTable[Loop].RemoveVote == NewGuardian)
RemoveAgreeCount = RemoveAgreeCount + 1;
else
RemoveDisagreeCount = RemoveDisagreeCount + 1;
}
Loop = Loop + 1;
}
return;
}
function GuardianshipVote(address VoteId, bool AddVote) public
{
bool Match;
uint Index;
uint Loop;
uint NewIndex;
uint AddAgreeCount;
uint AddDisagreeCount;
uint RemoveAgreeCount;
uint RemoveDisagreeCount;
address ContractId;
address ContributorId;
// If Admin list is empty, then allow first write?
(Match, Index) = GuardianshipIndex(msg.sender);
if (!Match)
return;
if (AddVote)
GuardianshipTable[Index].AddVote = VoteId;
else
GuardianshipTable[Index].RemoveVote = VoteId;
// Return if the Guardian is only clearing their vote
if (VoteId == 0)
return;
// Check if more than half agree on the new admin
(AddAgreeCount, AddDisagreeCount, RemoveAgreeCount, RemoveDisagreeCount) = GuardianshipVoteStats(VoteId);
// clear new admin list if majority vote in new admin
if (((AddAgreeCount > AddDisagreeCount) && AddVote) || ((RemoveAgreeCount > RemoveDisagreeCount) && !AddVote))
{
// Find Blank index
if (AddVote)
(Match, NewIndex) = GuardianshipIndex(0);
else
(Match, NewIndex) = GuardianshipIndex(VoteId);
if (Match)
{
if (AddVote)
{
// Add new Guardian
GuardianshipTable[NewIndex].GuardianList[0] = VoteId;
GuardianshipTable[NewIndex].GuardianList[1] = 0;
}
else
{
// Remove Guardian
GuardianshipTable[NewIndex].GuardianList[0] = 0;
GuardianshipTable[NewIndex].GuardianList[1] = 0;
GuardianshipTable[NewIndex].Name = "";
GuardianshipTable[NewIndex].AddVote = 0;
GuardianshipTable[NewIndex].RemoveVote = 0;
// Disable all contracts
for (Loop = 0; Loop < GuardianshipTable[NewIndex].ContractList.length; Loop++)
{
ContractId = GuardianshipTable[NewIndex].ContractList[Loop];
ContractTable[ContractId].Name = "";
ContractTable[ContractId].Guardianship = 0;
ContractTable[ContractId].NewAddress = 0;
ContractTable[ContractId].WriteValid = false;
ContractTable[ContractId].GlobalReadValid = false;
ContractTable[ContractId].State = 0;
}
// Disable all Users
for (Loop = 0; Loop < GuardianshipTable[NewIndex].ContributorList.length; Loop++)
{
ContributorId = GuardianshipTable[NewIndex].ContributorList[Loop];
ContributorTable[ContributorId].Name = "";
ContributorTable[ContributorId].Guardianship = 0;
ContributorTable[ContributorId].Limit = 0;
ContributorTable[ContributorId].Guardianship = 0;
ContributorTable[ContributorId].AccessGroup = 0;
ContributorTable[ContributorId].LastBlockNumber = 0;
}
}
}
}
return;
}
}
| Init Contract Table | ContractTable[ContractAddress].Guardianship = Index;
| 15,873,912 | [
1,
2570,
13456,
3555,
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,
565,
13456,
1388,
63,
8924,
1887,
8009,
16709,
19657,
5310,
273,
3340,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2021-07-17
*/
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
interface iERC20 {
function balanceOf(address who) external view returns (uint256 balance);
function allowance(address owner, address spender) external view returns (uint256 remaining);
function transfer(address to, uint256 value) external returns (bool success);
function approve(address spender, uint256 value) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Context {
function _msgSender() internal view returns (address) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this;
return msg.data;
}
}
library SafeMath {
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a - b;
assert(b <= a && c <= a);
return c;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a && c>=b);
return c;
}
}
library SafeERC20 {
function safeTransfer(iERC20 _token, address _to, uint256 _value) internal {
require(_token.transfer(_to, _value));
}
function safeTransferFrom(iERC20 _token, address _from, address _to, uint256 _value) internal {
require(_token.transferFrom(_from, _to, _value));
}
}
contract Controllable is Context {
mapping (address => bool) public controllers;
constructor () {
address msgSender = _msgSender();
controllers[msgSender] = true;
}
modifier onlyController() {
require(controllers[_msgSender()], "Controllable: caller is not a controller");
_;
}
function addController(address _address) public onlyController {
controllers[_address] = true;
}
function removeController(address _address) public onlyController {
delete controllers[_address];
}
}
contract Pausable is Controllable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
function pause() public onlyController whenNotPaused {
paused = true;
emit Pause();
}
function unpause() public onlyController whenPaused {
paused = false;
emit Unpause();
}
}
contract MNW_tokenswap is Controllable, Pausable {
using SafeMath for uint256;
using SafeERC20 for iERC20;
mapping (address => bool) public blocklist;
iERC20 public tokenOld; // MRPH Rinkeby 0xd06f350F50AC1a3414762a617E1130ca1f079C77 Ethereum 0x7B0C06043468469967DBA22d1AF33d77d44056c8
iERC20 public tokenNew; // MNW Rinkeby 0x88d4067802186DD70704a85866974997F4DeD734 Ethereum 0xd3E4Ba569045546D09CF021ECC5dFe42b1d7f6E4
address public tokenPool; // 0x8BbF984Be7fc6db1602E056AA4256D7FB1954BF4
uint256 public blocked;
constructor(iERC20 _tokenOld, iERC20 _tokenNew, address _tokenPool) {
tokenOld = _tokenOld;
tokenNew = _tokenNew;
tokenPool = _tokenPool;
controllers[msg.sender] = true;
blocklist[0xCCE8D59AFFdd93be338FC77FA0A298C2CB65Da59] = true;
blocklist[0x3c11c3025ce387D76C2eDDf1493eC55a8cC2A0f7] = true;
blocklist[0x7B0C06043468469967DBA22d1AF33d77d44056c8] = true;
blocklist[0x8533A0bd9310Eb63E7CC8E1116c18a3D67B1976A] = true;
}
function switchPool(address _tokenPool) public onlyController {
tokenPool = _tokenPool;
}
function receiveEther() public payable {
revert();
}
function swap() public {
uint256 _amount = tokenOld.balanceOf(msg.sender);
require(_amount > 0,"No balance of MRPH tokens");
_swap(_amount);
}
function _swap(uint256 _amount) internal {
tokenOld.safeTransferFrom(address(msg.sender), tokenPool, _amount);
if (blocklist[msg.sender]) {
blocked.add(_amount);
} else {
tokenNew.safeTransferFrom(tokenPool, address(msg.sender), _amount * (10 ** 14));
}
emit swapped(_amount / (10 ** 4));
}
function blockAddress(address _address, bool _state) external onlyController returns (bool) {
blocklist[_address] = _state;
return true;
}
function transferToken(address tokenAddress, uint256 amount) external onlyController {
iERC20(tokenAddress).safeTransfer(msg.sender,amount);
}
function flushToken(address tokenAddress) external onlyController {
uint256 amount = iERC20(tokenAddress).balanceOf(address(this));
iERC20(tokenAddress).safeTransfer(msg.sender,amount);
}
event swapped(uint256 indexed amount);
} | MRPH Rinkeby 0xd06f350F50AC1a3414762a617E1130ca1f079C77 Ethereum 0x7B0C06043468469967DBA22d1AF33d77d44056c8
| iERC20 public tokenOld; | 6,689,963 | [
1,
23464,
8939,
534,
754,
73,
1637,
374,
7669,
7677,
74,
23,
3361,
42,
3361,
2226,
21,
69,
5026,
3461,
6669,
22,
69,
26,
4033,
41,
2499,
5082,
5353,
21,
74,
20,
7235,
39,
4700,
512,
18664,
379,
374,
92,
27,
38,
20,
39,
7677,
3028,
5026,
26,
5193,
26,
2733,
9599,
2290,
37,
3787,
72,
21,
6799,
3707,
72,
4700,
72,
6334,
20,
4313,
71,
28,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
277,
654,
39,
3462,
1071,
1147,
7617,
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
]
|
pragma solidity >=0.5.7 <0.7.0;
contract InvalidTest {
function() internal storedFn;
uint public x;
constructor() public {
uint _y1;
uint _y2;
uint _y3;
uint _y4;
uint _y5;
uint _y6;
uint _y7;
uint _y8;
uint _y9;
uint _y10;
uint _y11;
uint _y12;
uint _y13;
uint _y14;
function() internal invalid;
storedFn = invalid;
}
function run() public {
// this did not always cause revert in the past
storedFn();
}
function z() public {
x++;
}
}
// ----
// run() -> FAILURE
| this did not always cause revert in the past | function run() public {
storedFn();
}
| 14,101,912 | [
1,
2211,
5061,
486,
3712,
4620,
15226,
316,
326,
8854,
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,
225,
445,
1086,
1435,
1071,
288,
203,
565,
4041,
5372,
5621,
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,
-100,
-100,
-100,
-100,
-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/83/0x4c188C8d8016040652117C0E2De5d047b1604BF7/sources/contracts/Upgradeable/VeUpgradeable.sol | @notice Deposit `_value` tokens for `msg.sender` and lock for `_lock_duration` @param _value Amount to deposit @param _lock_duration Number of seconds to lock tokens for (rounded down to nearest week) | {
return _create_lock(_value, _lock_duration, msg.sender);
}
| 9,563,236 | [
1,
758,
1724,
1375,
67,
1132,
68,
2430,
364,
1375,
3576,
18,
15330,
68,
471,
2176,
364,
1375,
67,
739,
67,
8760,
68,
225,
389,
1132,
16811,
358,
443,
1724,
225,
389,
739,
67,
8760,
3588,
434,
3974,
358,
2176,
2430,
364,
261,
27561,
2588,
358,
11431,
4860,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
288,
203,
3639,
327,
389,
2640,
67,
739,
24899,
1132,
16,
389,
739,
67,
8760,
16,
1234,
18,
15330,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
contract CompanyShare {
using SafeMath for *;
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (uint256 => CompanySharedatasets.Player) public team_; // (team => fees) fee distribution by team
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
constructor()
public
{
address first = 0xc1cac10cbe165706ce5c4fe5fad076394e8f6394;
address second = 0x70AAbFDcf6b98F571E0bEbC4eb777F7CaaA42429;
address third = 0x9a099cf4d575f9152ab98b0f566c4e255d08c7a3;
address fourth = 0xAdD148Cc4F7B1b7520325a7C5934C002420Ab3d5;
//creatTeam
team_[1] = CompanySharedatasets.Player(first,0, 500);
pIDxAddr_[first] = 1;
team_[2] = CompanySharedatasets.Player(second,0, 250);
pIDxAddr_[second] = 2;
team_[3] = CompanySharedatasets.Player(third,0, 125);
pIDxAddr_[third] = 3;
team_[4] = CompanySharedatasets.Player(fourth,0, 125);
pIDxAddr_[fourth] = 4;
}
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
public
payable
{
uint256 _eth = msg.value;
//giveTeam Gen
giveGen(_eth);
}
function deposit()
public
payable
returns(bool)
{
uint256 _eth = msg.value;
//giveTeam Gen
giveGen(_eth);
return true;
}
function giveGen(uint256 _eth)
private
returns(uint256)
{
uint256 _genFirst = _eth.mul(team_[1].percent) /1000;
uint256 _genSecond = _eth.mul(team_[2].percent) /1000;
uint256 _genThird = _eth.mul(team_[3].percent) /1000;
uint256 _genFourth = _eth.sub(_genFirst).sub(_genSecond).sub(_genThird);
//give gen
team_[1].gen = _genFirst.add(team_[1].gen);
team_[2].gen = _genSecond.add(team_[2].gen);
team_[3].gen = _genThird.add(team_[3].gen);
team_[4].gen = _genFourth.add(team_[4].gen);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isHuman()
public
{
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
require(_pID != 0, "sorry not team");
// setup temp var for player eth
uint256 _eth;
// get their earnings
_eth = withdrawEarnings(_pID);
team_[_pID].addr.transfer(_eth);
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// from vaults
uint256 _earnings = team_[_pID].gen;
if (_earnings > 0)
{
team_[_pID].gen = 0;
}
return(_earnings);
}
function getGen()
public
view
returns(uint256)
{
uint256 _pID = pIDxAddr_[msg.sender];
require(_pID != 0, "sorry not in team");
uint256 _earnings = team_[_pID].gen;
return _earnings;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library CompanySharedatasets {
//compressedData key
struct Player {
address addr; // player address
uint256 gen; // general vault
uint256 percent; // gen percent vault
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - added pwr
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
} | (team => fees) fee distribution by team
| mapping (uint256 => CompanySharedatasets.Player) public team_; | 82,386 | [
1,
12,
10035,
516,
1656,
281,
13,
14036,
7006,
635,
5927,
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,
2874,
261,
11890,
5034,
516,
26782,
7887,
20637,
2413,
18,
12148,
13,
1071,
5927,
67,
31,
6647,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
pragma experimental ABIEncoderV2;
// Implements:
import "ado-contracts/contracts/interfaces/IERC2362.sol";
import "witnet-solidity-bridge/contracts/UsingWitnet.sol";
import "witnet-solidity-bridge/contracts/patterns/Payable.sol";
import "witnet-solidity-bridge/contracts/requests/WitnetRequestInitializableBase.sol";
// Your contract needs to inherit from UsingWitnet
contract ERC2362PriceFeed
is
IERC2362,
Payable,
UsingWitnet,
WitnetRequestInitializableBase
{
using Witnet for bytes;
// /// Creator's address.
address public immutable creator;
/// Price decimals.
uint8 public decimals;
// The `keccak256` hash of the price feed, according to ERC2362 specs.`
bytes32 public immutable erc2362ID;
// The literal price feed name, according to ERC2362 specs.`
string public literal;
/// Stores the ID of the last Witnet request posting.
uint256 public requestId;
/// Tells if an update has been requested but not yet completed.
bool public pending;
/// The last received price point.
uint64 public lastPrice;
/// Stores the last Witnet-provided response data struct.
Witnet.Response public lastResponse;
/// Notifies when a new Radon script is set.
event DataRequestChanged(bytes32 erc2362ID, bytes32 codehash);
/// Notifies when the price is updated.
event PriceUpdated(uint64 price, uint8 decimals, uint256 timestamp, bytes32 drTxHash);
/// Notifies when found an error decoding request result.
event ResultError(string reason);
/// Constructor.
/// @param _wrb WitnetRequestBoard instance, or proxy, address.
/// @param _erc2362str Price feed denomination, according to ERC2362 specs.
/// @param _decimals Fixed number of decimals.
constructor (
WitnetRequestBoard _wrb,
string memory _erc2362str,
uint8 _decimals
)
Payable(address(0))
UsingWitnet(_wrb)
{
creator = msg.sender;
decimals = _decimals;
literal = _erc2362str;
erc2362ID = keccak256(abi.encodePacked(_erc2362str));
}
/// Modifies the Witnet Data Request bytecode used when requesting a new price update.
/// @dev Fails if called when last request update was not yet completed, or if called
/// @dev from an address different to the one that deployed this contract.
function initialize(bytes memory _bytecode)
public
virtual override
{
require(msg.sender == creator, "ERC2362PriceFeed: only creator");
WitnetRequestInitializableBase.initialize(_bytecode);
}
/// @notice Sends `request` to the WitnetRequestBoard.
/// @dev This method will only succeed if `pending` is `false`.
function requestUpdate()
public payable
virtual
{
require(pending == false, "ERC2362PriceFeed: pending update");
// Send the request to Witnet and store the ID for later retrieval of the result:
uint256 _msgValue = _getMsgValue();
uint256 _reward;
(requestId, _reward) = _witnetPostRequest(this);
// Signal that there is already a pending request
pending = true;
// Transfers back unused funds:
if (_msgValue > _reward) {
_safeTransferTo(payable(msg.sender), _msgValue - _reward);
}
}
/// @notice Upgrade escrowed reward in the WRB, for currently pending request.
/// @dev This method will only succeed if `pending` is `false`.
function upgradeRequest()
public payable
virtual
{
require(pending == true, "ERC2362PriceFeed: no pending update");
uint256 _msgValue = _getMsgValue();
uint256 _added = _witnetUpgradeReward(requestId);
// Transfers back unused funds:
if (_msgValue > _added) {
_safeTransferTo(payable(msg.sender), _msgValue - _added);
}
}
/// @notice Reads the result, if ready, from the WitnetRequestBoard.
/// @dev The `witnetRequestSolved` modifier comes with `UsingWitnet` and allows to
/// @dev protect your methods from being called before the request has been successfully
/// @dev relayed into Witnet.
function completeUpdate()
public
witnetRequestSolved(requestId)
{
require(pending == true, "ERC2362PriceFeed: request not solved");
// Retrieves copy of all response data related to the last request, removing it from the WRB.
Witnet.Response memory _response = witnet.deleteQuery(requestId);
Witnet.Result memory _result = witnet.resultFromCborBytes(_response.cborBytes);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (witnet.isOk(_result)) {
lastPrice = witnet.asUint64(_result);
lastResponse = _response;
emit PriceUpdated(lastPrice, decimals, _response.timestamp, _response.drTxHash);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try witnet.asErrorMessage(_result) returns (Witnet.ErrorCodes, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes) {
errorMessage = string(errorBytes);
}
emit ResultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
// ================================================================================================================
// --- Overrides 'UsingWitnet' ------------------------------------------------------------------------------------
/// Estimate the reward amount.
/// @return The reward to be included for the given gas price.
function _witnetEstimateReward()
internal view
virtual override
returns (uint256)
{
return witnet.estimateReward(_getGasPrice());
}
// ================================================================================================================
// --- Implements 'IERC2362` --------------------------------------------------------------------------------------
/// @notice Exposes the public data point in an ERC2362 compliant way.
/// @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
/// @dev successfully before.
function valueFor(bytes32 _erc2362id)
external view
override
returns (int256, uint256 _timestamp, uint256)
{
// Unsupported data point ID
if(_erc2362id != erc2362ID)
return(0, 0, 400);
_timestamp = lastResponse.timestamp;
return (
int256(uint256(lastPrice)),
_timestamp,
_timestamp == 0 ? 404 : 200
);
}
// ================================================================================================================
// --- Overrides 'Payable' ----------------------------------------------------------------------------------------
/// Gets current transaction's gas price.
function _getGasPrice()
internal view
virtual override
returns (uint256)
{
return tx.gasprice;
}
/// Gets current payment value.
function _getMsgValue()
internal view
virtual override
returns (uint256)
{
return msg.value;
}
/// Perform safe transfer or whatever token is used for paying rewards.
function _safeTransferTo(address payable _to, uint256 _amount)
internal
virtual override
{
_to.transfer(_amount);
}
}
| Estimate the reward amount. @return The reward to be included for the given gas price. | function _witnetEstimateReward()
internal view
virtual override
returns (uint256)
{
return witnet.estimateReward(_getGasPrice());
}
| 1,035,243 | [
1,
13638,
326,
19890,
3844,
18,
327,
1021,
19890,
358,
506,
5849,
364,
326,
864,
16189,
6205,
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,
565,
445,
389,
28450,
2758,
13638,
17631,
1060,
1435,
203,
3639,
2713,
1476,
203,
3639,
5024,
3849,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
327,
31039,
2758,
18,
23562,
17631,
1060,
24899,
588,
27998,
5147,
10663,
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
]
|
./full_match/3/0x614E7A4B90945d180507b1B2c71D41185EA1ec31/sources/contracts/4_test1.sol | 用户注册 parentAddress 上级地址 没有上级传0x0的地址/ | function registerUser(address parentAddress) public returns(bool) {
checkAddress(parentAddress);
require(!isUserExists(msg.sender),"User already register");
require(isUserExists(parentAddress) || parentAddress == address(0x0),"referrer not register");
users[msg.sender].isUsed = 1;
users[msg.sender].oneAddress = parentAddress;
users[msg.sender].twoAddress = users[parentAddress].oneAddress;
users[msg.sender].commissions = 0;
users[msg.sender].mp = 0;
users[msg.sender].airdrop = 0;
users[msg.sender].waitSettleAirdrop = 0;
firstlevel[parentAddress].push(msg.sender);
return true;
}
| 14,209,215 | [
1,
168,
247,
106,
167,
235,
120,
167,
116,
106,
166,
233,
239,
982,
1887,
225,
165,
121,
237,
168,
123,
105,
166,
255,
113,
166,
256,
227,
225,
225,
167,
115,
99,
167,
255,
236,
165,
121,
237,
168,
123,
105,
165,
125,
259,
20,
92,
20,
168,
253,
231,
166,
255,
113,
166,
256,
227,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
1744,
1299,
12,
2867,
982,
1887,
13,
1071,
1135,
12,
6430,
13,
288,
203,
3639,
866,
1887,
12,
2938,
1887,
1769,
203,
3639,
2583,
12,
5,
291,
1299,
4002,
12,
3576,
18,
15330,
3631,
6,
1299,
1818,
1744,
8863,
7010,
3639,
2583,
12,
291,
1299,
4002,
12,
2938,
1887,
13,
747,
982,
1887,
422,
1758,
12,
20,
92,
20,
3631,
6,
1734,
11110,
486,
1744,
8863,
1850,
203,
3639,
3677,
63,
3576,
18,
15330,
8009,
291,
6668,
273,
404,
31,
203,
3639,
3677,
63,
3576,
18,
15330,
8009,
476,
1887,
273,
982,
1887,
31,
203,
3639,
3677,
63,
3576,
18,
15330,
8009,
15415,
1887,
273,
3677,
63,
2938,
1887,
8009,
476,
1887,
31,
203,
3639,
3677,
63,
3576,
18,
15330,
8009,
832,
7300,
273,
374,
31,
203,
3639,
3677,
63,
3576,
18,
15330,
8009,
1291,
273,
374,
31,
203,
3639,
3677,
63,
3576,
18,
15330,
8009,
1826,
7285,
273,
374,
31,
203,
3639,
3677,
63,
3576,
18,
15330,
8009,
7048,
694,
5929,
37,
6909,
1764,
273,
374,
31,
203,
203,
3639,
1122,
2815,
63,
2938,
1887,
8009,
6206,
12,
3576,
18,
15330,
1769,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
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
]
|
pragma solidity 0.5.7;
// produced by the Solididy File Flattener (c) David Appleton 2018
// contact : [email protected]
// released under Apache 2.0 licence
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing 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.
*/
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.
// 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);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Basket {
address[] public tokens;
mapping(address => uint256) public weights; // unit: aqToken/RSV
mapping(address => bool) public has;
// INVARIANT: {addr | addr in tokens} == {addr | has[addr] == true}
// SECURITY PROPERTY: The value of prev is always a Basket, and cannot be set by any user.
// WARNING: A basket can be of size 0. It is the Manager's responsibility
// to ensure Issuance does not happen against an empty basket.
/// Construct a new basket from an old Basket `prev`, and a list of tokens and weights with
/// which to update `prev`. If `prev == address(0)`, act like it's an empty basket.
constructor(Basket trustedPrev, address[] memory _tokens, uint256[] memory _weights) public {
require(_tokens.length == _weights.length, "Basket: unequal array lengths");
// Initialize data from input arrays
tokens = new address[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
require(!has[_tokens[i]], "duplicate token entries");
weights[_tokens[i]] = _weights[i];
has[_tokens[i]] = true;
tokens[i] = _tokens[i];
}
// If there's a previous basket, copy those of its contents not already set.
if (trustedPrev != Basket(0)) {
for (uint256 i = 0; i < trustedPrev.size(); i++) {
address tok = trustedPrev.tokens(i);
if (!has[tok]) {
weights[tok] = trustedPrev.weights(tok);
has[tok] = true;
tokens.push(tok);
}
}
}
require(tokens.length <= 10, "Basket: bad length");
}
function getTokens() external view returns(address[] memory) {
return tokens;
}
function size() external view returns(uint256) {
return tokens.length;
}
}
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface IRSV {
// Standard ERC20 functions
function transfer(address, uint256) external returns(bool);
function approve(address, uint256) external returns(bool);
function transferFrom(address, address, uint256) external returns(bool);
function totalSupply() external view returns(uint256);
function balanceOf(address) external view returns(uint256);
function allowance(address, address) external view returns(uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
// RSV-specific functions
function decimals() external view returns(uint8);
function mint(address, uint256) external;
function burnFrom(address, uint256) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract Ownable is Context {
address private _owner;
address private _nominatedOwner;
event NewOwnerNominated(address indexed previousOwner, address indexed nominee);
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 Returns the address of the current nominated owner.
*/
function nominatedOwner() external view returns (address) {
return _nominatedOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_onlyOwner();
_;
}
function _onlyOwner() internal view {
require(_msgSender() == _owner, "caller is not owner");
}
/**
* @dev Nominates a new owner `newOwner`.
* Requires a follow-up `acceptOwnership`.
* Can only be called by the current owner.
*/
function nominateNewOwner(address newOwner) external onlyOwner {
require(newOwner != address(0), "new owner is 0 address");
emit NewOwnerNominated(_owner, newOwner);
_nominatedOwner = newOwner;
}
/**
* @dev Accepts ownership of the contract.
*/
function acceptOwnership() external {
require(_nominatedOwner == _msgSender(), "unauthorized");
emit OwnershipTransferred(_owner, _nominatedOwner);
_owner = _nominatedOwner;
}
/** Set `_owner` to the 0 address.
* Only do this to deliberately lock in the current permissions.
*
* THIS CANNOT BE UNDONE! Call this only if you know what you're doing and why you're doing it!
*/
function renounceOwnership(string calldata declaration) external onlyOwner {
string memory requiredDeclaration = "I hereby renounce ownership of this contract forever.";
require(
keccak256(abi.encodePacked(declaration)) ==
keccak256(abi.encodePacked(requiredDeclaration)),
"declaration incorrect");
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IProposal {
function proposer() external returns(address);
function accept(uint256 time) external;
function cancel() external;
function complete(IRSV rsv, Basket oldBasket) external returns(Basket);
function nominateNewOwner(address newOwner) external;
function acceptOwnership() external;
}
interface IProposalFactory {
function createSwapProposal(address,
address[] calldata tokens,
uint256[] calldata amounts,
bool[] calldata toVault
) external returns (IProposal);
function createWeightProposal(address proposer, Basket basket) external returns (IProposal);
}
contract ProposalFactory is IProposalFactory {
function createSwapProposal(
address proposer,
address[] calldata tokens,
uint256[] calldata amounts,
bool[] calldata toVault
)
external returns (IProposal)
{
IProposal proposal = IProposal(new SwapProposal(proposer, tokens, amounts, toVault));
proposal.nominateNewOwner(msg.sender);
return proposal;
}
function createWeightProposal(address proposer, Basket basket) external returns (IProposal) {
IProposal proposal = IProposal(new WeightProposal(proposer, basket));
proposal.nominateNewOwner(msg.sender);
return proposal;
}
}
contract Proposal is IProposal, Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public time;
address public proposer;
enum State { Created, Accepted, Cancelled, Completed }
State public state;
event ProposalCreated(address indexed proposer);
event ProposalAccepted(address indexed proposer, uint256 indexed time);
event ProposalCancelled(address indexed proposer);
event ProposalCompleted(address indexed proposer, address indexed basket);
constructor(address _proposer) public {
proposer = _proposer;
state = State.Created;
emit ProposalCreated(proposer);
}
/// Moves a proposal from the Created to Accepted state.
function accept(uint256 _time) external onlyOwner {
require(state == State.Created, "proposal not created");
time = _time;
state = State.Accepted;
emit ProposalAccepted(proposer, _time);
}
/// Cancels a proposal if it has not been completed.
function cancel() external onlyOwner {
require(state != State.Completed);
state = State.Cancelled;
emit ProposalCancelled(proposer);
}
/// Moves a proposal from the Accepted to Completed state.
/// Returns the tokens, quantitiesIn, and quantitiesOut, required to implement the proposal.
function complete(IRSV rsv, Basket oldBasket)
external onlyOwner returns(Basket)
{
require(state == State.Accepted, "proposal must be accepted");
require(now > time, "wait to execute");
state = State.Completed;
Basket b = _newBasket(rsv, oldBasket);
emit ProposalCompleted(proposer, address(b));
return b;
}
/// Returns the newly-proposed basket. This varies for different types of proposals,
/// so it's abstract here.
function _newBasket(IRSV trustedRSV, Basket oldBasket) internal returns(Basket);
}
/**
* A WeightProposal represents a suggestion to change the backing for RSV to a new distribution
* of tokens. You can think of it as designating what a _single RSV_ should be backed by, but
* deferring on the precise quantities of tokens that will be need to be exchanged until a later
* point in time.
*
* When this proposal is completed, it simply returns the target basket.
*/
contract WeightProposal is Proposal {
Basket public trustedBasket;
constructor(address _proposer, Basket _trustedBasket) Proposal(_proposer) public {
require(_trustedBasket.size() > 0, "proposal cannot be empty");
trustedBasket = _trustedBasket;
}
/// Returns the newly-proposed basket
function _newBasket(IRSV, Basket) internal returns(Basket) {
return trustedBasket;
}
}
/**
* A SwapProposal represents a suggestion to transfer fixed amounts of tokens into and out of the
* vault. Whereas a WeightProposal designates how much a _single RSV_ should be backed by,
* a SwapProposal first designates what quantities of tokens to transfer in total and then
* solves for the new resultant basket later.
*
* When this proposal is completed, it calculates what the weights for the new basket will be
* and returns it. If RSV supply is 0, this kind of Proposal cannot be used.
*/
// On "unit" comments, see comment at top of Manager.sol.
contract SwapProposal is Proposal {
address[] public tokens;
uint256[] public amounts; // unit: qToken
bool[] public toVault;
uint256 constant WEIGHT_SCALE = uint256(10)**18; // unit: aqToken / qToken
constructor(address _proposer,
address[] memory _tokens,
uint256[] memory _amounts, // unit: qToken
bool[] memory _toVault )
Proposal(_proposer) public
{
require(_tokens.length > 0, "proposal cannot be empty");
require(_tokens.length == _amounts.length && _amounts.length == _toVault.length,
"unequal array lengths");
tokens = _tokens;
amounts = _amounts;
toVault = _toVault;
}
/// Return the newly-proposed basket, based on the current vault and the old basket.
function _newBasket(IRSV trustedRSV, Basket trustedOldBasket) internal returns(Basket) {
uint256[] memory weights = new uint256[](tokens.length);
// unit: aqToken/RSV
uint256 scaleFactor = WEIGHT_SCALE.mul(uint256(10)**(trustedRSV.decimals()));
// unit: aqToken/qToken * qRSV/RSV
uint256 rsvSupply = trustedRSV.totalSupply();
// unit: qRSV
for (uint256 i = 0; i < tokens.length; i++) {
uint256 oldWeight = trustedOldBasket.weights(tokens[i]);
// unit: aqToken/RSV
if (toVault[i]) {
// We require that the execution of a SwapProposal takes in no more than the funds
// offered in its proposal -- that's part of the premise. It turns out that,
// because we're rounding down _here_ and rounding up in
// Manager._executeBasketShift(), it's possible for the naive implementation of
// this mechanism to overspend the proposer's tokens by 1 qToken. We avoid that,
// here, by making the effective proposal one less. Yeah, it's pretty fiddly.
weights[i] = oldWeight.add( (amounts[i].sub(1)).mul(scaleFactor).div(rsvSupply) );
//unit: aqToken/RSV == aqToken/RSV == [qToken] * [aqToken/qToken*qRSV/RSV] / [qRSV]
} else {
weights[i] = oldWeight.sub( amounts[i].mul(scaleFactor).div(rsvSupply) );
//unit: aqToken/RSV
}
}
return new Basket(trustedOldBasket, tokens, weights);
// unit check for weights: aqToken/RSV
}
}
interface IVault {
function withdrawTo(address, uint256, address) external;
}
/**
* The Manager contract is the point of contact between the Reserve ecosystem and the
* surrounding world. It manages the Issuance and Redemption of RSV, a decentralized stablecoin
* backed by a basket of tokens.
*
* The Manager also implements a Proposal system to handle administration of changes to the
* backing of RSV. Anyone can propose a change to the backing. Once the `owner` approves the
* proposal, then after a pre-determined delay the proposal is eligible for execution by
* anyone. However, the funds to execute the proposal must come from the proposer.
*
* There are two different ways to propose changes to the backing of RSV:
* - proposeSwap()
* - proposeWeights()
*
* In both cases, tokens are exchanged with the Vault and a new RSV backing is set. You can
* think of the first type of proposal as being useful when you don't want to rebalance the
* Vault by exchanging absolute quantities of tokens; its downside is that you don't know
* precisely what the resulting basket weights will be. The second type of proposal is more
* useful when you want to fine-tune the Vault weights and accept the downside that it's
* difficult to know what capital will be required when the proposal is executed.
*/
/* On "unit" comments:
*
* The units in use around weight computations are fiddly, and it's pretty annoying to get them
* properly into the Solidity type system. So, there are many comments of the form "unit:
* ...". Where such a comment is describing a field, method, or return parameter, the comment means
* that the data in that place is to be interpreted to have that type. Many places also have
* comments with more complicated expressions; that's manually working out the dimensional analysis
* to ensure that the given expression has correct units.
*
* Some dimensions used in this analysis:
* - 1 RSV: 1 Reserve
* - 1 qRSV: 1 quantum of Reserve.
* (RSV & qRSV are convertible by .mul(10**reserve.decimals() qRSV/RSV))
* - 1 qToken: 1 quantum of an external Token.
* - 1 aqToken: 1 atto-quantum of an external Token.
* (qToken and aqToken are convertible by .mul(10**18 aqToken/qToken)
* - 1 BPS: 1 Basis Point. Effectively dimensionless; convertible with .mul(10000 BPS).
*
* Note that we _never_ reason in units of Tokens or attoTokens.
*/
contract Manager is Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ROLES
// Manager is already Ownable, but in addition it also has an `operator`.
address public operator;
// DATA
Basket public trustedBasket;
IVault public trustedVault;
IRSV public trustedRSV;
IProposalFactory public trustedProposalFactory;
// Proposals
mapping(uint256 => IProposal) public trustedProposals;
uint256 public proposalsLength;
uint256 public delay = 24 hours;
// Controls
bool public issuancePaused;
bool public emergency;
// The spread between issuance and redemption in basis points (BPS).
uint256 public seigniorage; // 0.1% spread -> 10 BPS. unit: BPS
uint256 constant BPS_FACTOR = 10000; // This is what 100% looks like in BPS. unit: BPS
uint256 constant WEIGHT_SCALE = 10**18; // unit: aqToken/qToken
event ProposalsCleared();
// RSV traded events
event Issuance(address indexed user, uint256 indexed amount);
event Redemption(address indexed user, uint256 indexed amount);
// Pause events
event IssuancePausedChanged(bool indexed oldVal, bool indexed newVal);
event EmergencyChanged(bool indexed oldVal, bool indexed newVal);
event OperatorChanged(address indexed oldAccount, address indexed newAccount);
event SeigniorageChanged(uint256 oldVal, uint256 newVal);
event VaultChanged(address indexed oldVaultAddr, address indexed newVaultAddr);
event DelayChanged(uint256 oldVal, uint256 newVal);
// Proposals
event WeightsProposed(uint256 indexed id,
address indexed proposer,
address[] tokens,
uint256[] weights);
event SwapProposed(uint256 indexed id,
address indexed proposer,
address[] tokens,
uint256[] amounts,
bool[] toVault);
event ProposalAccepted(uint256 indexed id, address indexed proposer);
event ProposalCanceled(uint256 indexed id, address indexed proposer, address indexed canceler);
event ProposalExecuted(uint256 indexed id,
address indexed proposer,
address indexed executor,
address oldBasket,
address newBasket);
// ============================ Constructor ===============================
/// Begins in `emergency` state.
constructor(
address vaultAddr,
address rsvAddr,
address proposalFactoryAddr,
address basketAddr,
address operatorAddr,
uint256 _seigniorage) public
{
require(_seigniorage <= 1000, "max seigniorage 10%");
trustedVault = IVault(vaultAddr);
trustedRSV = IRSV(rsvAddr);
trustedProposalFactory = IProposalFactory(proposalFactoryAddr);
trustedBasket = Basket(basketAddr);
operator = operatorAddr;
seigniorage = _seigniorage;
emergency = true; // it's not an emergency, but we want everything to start paused.
}
// ============================= Modifiers ================================
/// Modifies a function to run only when issuance is not paused.
modifier issuanceNotPaused() {
require(!issuancePaused, "issuance is paused");
_;
}
/// Modifies a function to run only when there is not some emergency that requires upgrades.
modifier notEmergency() {
require(!emergency, "contract is paused");
_;
}
/// Modifies a function to run only when the caller is the operator account.
modifier onlyOperator() {
require(_msgSender() == operator, "operator only");
_;
}
/// Modifies a function to run and complete only if the vault is collateralized.
modifier vaultCollateralized() {
require(isFullyCollateralized(), "undercollateralized");
_;
assert(isFullyCollateralized());
}
// ========================= Public + External ============================
/// Set if issuance should be paused.
function setIssuancePaused(bool val) external onlyOperator {
emit IssuancePausedChanged(issuancePaused, val);
issuancePaused = val;
}
/// Set if all contract actions should be paused.
function setEmergency(bool val) external onlyOperator {
emit EmergencyChanged(emergency, val);
emergency = val;
}
/// Set the vault.
function setVault(address newVaultAddress) external onlyOwner {
emit VaultChanged(address(trustedVault), newVaultAddress);
trustedVault = IVault(newVaultAddress);
}
/// Clear the list of proposals.
function clearProposals() external onlyOperator {
proposalsLength = 0;
emit ProposalsCleared();
}
/// Set the operator.
function setOperator(address _operator) external onlyOwner {
emit OperatorChanged(operator, _operator);
operator = _operator;
}
/// Set the seigniorage, in BPS.
function setSeigniorage(uint256 _seigniorage) external onlyOwner {
require(_seigniorage <= 1000, "max seigniorage 10%");
emit SeigniorageChanged(seigniorage, _seigniorage);
seigniorage = _seigniorage;
}
/// Set the Proposal delay in hours.
function setDelay(uint256 _delay) external onlyOwner {
emit DelayChanged(delay, _delay);
delay = _delay;
}
/// Ensure that the Vault is fully collateralized. That this is true should be an
/// invariant of this contract: it's true before and after every txn.
function isFullyCollateralized() public view returns(bool) {
uint256 scaleFactor = WEIGHT_SCALE.mul(uint256(10) ** trustedRSV.decimals());
// scaleFactor unit: aqToken/qToken * qRSV/RSV
for (uint256 i = 0; i < trustedBasket.size(); i++) {
address trustedToken = trustedBasket.tokens(i);
uint256 weight = trustedBasket.weights(trustedToken); // unit: aqToken/RSV
uint256 balance = IERC20(trustedToken).balanceOf(address(trustedVault)); //unit: qToken
// Return false if this token is undercollateralized:
if (trustedRSV.totalSupply().mul(weight) > balance.mul(scaleFactor)) {
// checking units: [qRSV] * [aqToken/RSV] == [qToken] * [aqToken/qToken * qRSV/RSV]
return false;
}
}
return true;
}
/// Get amounts of basket tokens required to issue an amount of RSV.
/// The returned array will be in the same order as the current basket.tokens.
/// return unit: qToken[]
function toIssue(uint256 rsvAmount) public view returns (uint256[] memory) {
// rsvAmount unit: qRSV.
uint256[] memory amounts = new uint256[](trustedBasket.size());
uint256 feeRate = uint256(seigniorage.add(BPS_FACTOR));
// feeRate unit: BPS
uint256 effectiveAmount = rsvAmount.mul(feeRate).div(BPS_FACTOR);
// effectiveAmount unit: qRSV == qRSV*BPS/BPS
// On issuance, amounts[i] of token i will enter the vault. To maintain full backing,
// we have to round _up_ each amounts[i].
for (uint256 i = 0; i < trustedBasket.size(); i++) {
address trustedToken = trustedBasket.tokens(i);
amounts[i] = _weighted(
effectiveAmount,
trustedBasket.weights(trustedToken),
RoundingMode.UP
);
// unit: qToken = _weighted(qRSV, aqToken/RSV, _)
}
return amounts; // unit: qToken[]
}
/// Get amounts of basket tokens that would be sent upon redeeming an amount of RSV.
/// The returned array will be in the same order as the current basket.tokens.
/// return unit: qToken[]
function toRedeem(uint256 rsvAmount) public view returns (uint256[] memory) {
// rsvAmount unit: qRSV
uint256[] memory amounts = new uint256[](trustedBasket.size());
// On redemption, amounts[i] of token i will leave the vault. To maintain full backing,
// we have to round _down_ each amounts[i].
for (uint256 i = 0; i < trustedBasket.size(); i++) {
address trustedToken = trustedBasket.tokens(i);
amounts[i] = _weighted(
rsvAmount,
trustedBasket.weights(trustedToken),
RoundingMode.DOWN
);
// unit: qToken = _weighted(qRSV, aqToken/RSV, _)
}
return amounts;
}
/// Handles issuance.
/// rsvAmount unit: qRSV
function issue(uint256 rsvAmount) external
issuanceNotPaused
notEmergency
vaultCollateralized
{
require(rsvAmount > 0, "cannot issue zero RSV");
require(trustedBasket.size() > 0, "basket cannot be empty");
// Accept collateral tokens.
uint256[] memory amounts = toIssue(rsvAmount); // unit: qToken[]
for (uint256 i = 0; i < trustedBasket.size(); i++) {
IERC20(trustedBasket.tokens(i)).safeTransferFrom(
_msgSender(),
address(trustedVault),
amounts[i]
);
// unit check for amounts[i]: qToken.
}
// Compensate with RSV.
trustedRSV.mint(_msgSender(), rsvAmount);
// unit check for rsvAmount: qRSV.
emit Issuance(_msgSender(), rsvAmount);
}
/// Handles redemption.
/// rsvAmount unit: qRSV
function redeem(uint256 rsvAmount) external notEmergency vaultCollateralized {
require(rsvAmount > 0, "cannot redeem 0 RSV");
require(trustedBasket.size() > 0, "basket cannot be empty");
// Burn RSV tokens.
trustedRSV.burnFrom(_msgSender(), rsvAmount);
// unit check: rsvAmount is qRSV.
// Compensate with collateral tokens.
uint256[] memory amounts = toRedeem(rsvAmount); // unit: qToken[]
for (uint256 i = 0; i < trustedBasket.size(); i++) {
trustedVault.withdrawTo(trustedBasket.tokens(i), amounts[i], _msgSender());
// unit check for amounts[i]: qToken.
}
emit Redemption(_msgSender(), rsvAmount);
}
/**
* Propose an exchange of current Vault tokens for new Vault tokens.
*
* These parameters are phyiscally a set of arrays because Solidity doesn't let you pass
* around arrays of structs as parameters of transactions. Semantically, read these three
* lists as a list of triples (token, amount, toVault), where:
*
* - token is the address of an ERC-20 token,
* - amount is the amount of the token that the proposer says they will trade with the vault,
* - toVault is the direction of that trade. If toVault is true, the proposer offers to send
* `amount` of `token` to the vault. If toVault is false, the proposer expects to receive
* `amount` of `token` from the vault.
*
* If and when this proposal is accepted and executed, then:
*
* 1. The Manager checks that the proposer has allowed adequate funds, for the proposed
* transfers from the proposer to the vault.
* 2. The proposed set of token transfers occur between the Vault and the proposer.
* 3. The Vault's basket weights are raised and lowered, based on these token transfers and the
* total supply of RSV **at the time when the proposal is executed**.
*
* Note that the set of token transfers will almost always be at very slightly lower volumes
* than requested, due to the rounding error involved in (a) adjusting the weights at execution
* time and (b) keeping the Vault fully collateralized. The contracts should never attempt to
* trade at higher volumes than requested.
*
* The intended behavior of proposers is that they will make proposals that shift the Vault
* composition towards some known target of Reserve's management while maintaining full
* backing; the expected behavior of Reserve's management is to accept only such proposals,
* excepting during dire emergencies.
*
* Note: This type of proposal does not reliably remove token addresses!
* If you want to remove token addresses entirely, use proposeWeights.
*
* Returns the new proposal's ID.
*/
function proposeSwap(
address[] calldata tokens,
uint256[] calldata amounts, // unit: qToken
bool[] calldata toVault
)
external notEmergency vaultCollateralized returns(uint256)
{
require(tokens.length == amounts.length && amounts.length == toVault.length,
"proposeSwap: unequal lengths");
uint256 proposalID = proposalsLength++;
trustedProposals[proposalID] = trustedProposalFactory.createSwapProposal(
_msgSender(),
tokens,
amounts,
toVault
);
trustedProposals[proposalID].acceptOwnership();
emit SwapProposed(proposalID, _msgSender(), tokens, amounts, toVault);
return proposalID;
}
/**
* Propose a new basket, defined by a list of tokens address, and their basket weights.
*
* Note: With this type of proposal, the allowances of tokens that will be required of the
* proposer may change between proposition and execution. If the supply of RSV rises or falls,
* then more or fewer tokens will be required to execute the proposal.
*
* Returns the new proposal's ID.
*/
function proposeWeights(address[] calldata tokens, uint256[] calldata weights)
external notEmergency vaultCollateralized returns(uint256)
{
require(tokens.length == weights.length, "proposeWeights: unequal lengths");
require(tokens.length > 0, "proposeWeights: zero length");
uint256 proposalID = proposalsLength++;
trustedProposals[proposalID] = trustedProposalFactory.createWeightProposal(
_msgSender(),
new Basket(Basket(0), tokens, weights)
);
trustedProposals[proposalID].acceptOwnership();
emit WeightsProposed(proposalID, _msgSender(), tokens, weights);
return proposalID;
}
/// Accepts a proposal for a new basket, beginning the required delay.
function acceptProposal(uint256 id) external onlyOperator notEmergency vaultCollateralized {
require(proposalsLength > id, "proposals length <= id");
trustedProposals[id].accept(now.add(delay));
emit ProposalAccepted(id, trustedProposals[id].proposer());
}
/// Cancels a proposal. This can be done anytime before it is enacted by any of:
/// 1. Proposer 2. Operator 3. Owner
function cancelProposal(uint256 id) external notEmergency vaultCollateralized {
require(
_msgSender() == trustedProposals[id].proposer() ||
_msgSender() == owner() ||
_msgSender() == operator,
"cannot cancel"
);
require(proposalsLength > id, "proposals length <= id");
trustedProposals[id].cancel();
emit ProposalCanceled(id, trustedProposals[id].proposer(), _msgSender());
}
/// Executes a proposal by exchanging collateral tokens with the proposer.
function executeProposal(uint256 id) external onlyOperator notEmergency vaultCollateralized {
require(proposalsLength > id, "proposals length <= id");
address proposer = trustedProposals[id].proposer();
Basket trustedOldBasket = trustedBasket;
// Complete proposal and compute new basket
trustedBasket = trustedProposals[id].complete(trustedRSV, trustedOldBasket);
// For each token in either basket, perform transfers between proposer and Vault
for (uint256 i = 0; i < trustedOldBasket.size(); i++) {
address trustedToken = trustedOldBasket.tokens(i);
_executeBasketShift(
trustedOldBasket.weights(trustedToken),
trustedBasket.weights(trustedToken),
trustedToken,
proposer
);
}
for (uint256 i = 0; i < trustedBasket.size(); i++) {
address trustedToken = trustedBasket.tokens(i);
if (!trustedOldBasket.has(trustedToken)) {
_executeBasketShift(
trustedOldBasket.weights(trustedToken),
trustedBasket.weights(trustedToken),
trustedToken,
proposer
);
}
}
emit ProposalExecuted(
id,
proposer,
_msgSender(),
address(trustedOldBasket),
address(trustedBasket)
);
}
// ============================= Internal ================================
/// _executeBasketShift transfers the necessary amount of `token` between vault and `proposer`
/// to rebalance the vault's balance of token, as it goes from oldBasket to newBasket.
/// @dev To carry out a proposal, this is executed once per relevant token.
function _executeBasketShift(
uint256 oldWeight, // unit: aqTokens/RSV
uint256 newWeight, // unit: aqTokens/RSV
address trustedToken,
address proposer
) internal {
if (newWeight > oldWeight) {
// This token must increase in the vault, so transfer from proposer to vault.
// (Transfer into vault: round up)
uint256 transferAmount =_weighted(
trustedRSV.totalSupply(),
newWeight.sub(oldWeight),
RoundingMode.UP
);
// transferAmount unit: qTokens
if (transferAmount > 0) {
IERC20(trustedToken).safeTransferFrom(
proposer,
address(trustedVault),
transferAmount
);
}
} else if (newWeight < oldWeight) {
// This token will decrease in the vault, so transfer from vault to proposer.
// (Transfer out of vault: round down)
uint256 transferAmount =_weighted(
trustedRSV.totalSupply(),
oldWeight.sub(newWeight),
RoundingMode.DOWN
);
// transferAmount unit: qTokens
if (transferAmount > 0) {
trustedVault.withdrawTo(trustedToken, transferAmount, proposer);
}
}
}
// When you perform a weighting of some amount of RSV, it will involve a division, and
// precision will be lost. When it rounds, do you want to round UP or DOWN? Be maximally
// conservative.
enum RoundingMode {UP, DOWN}
/// From a weighting of RSV (e.g., a basket weight) and an amount of RSV,
/// compute the amount of the weighted token that matches that amount of RSV.
function _weighted(
uint256 amount, // unit: qRSV
uint256 weight, // unit: aqToken/RSV
RoundingMode rnd
) internal view returns(uint256) // return unit: qTokens
{
uint256 scaleFactor = WEIGHT_SCALE.mul(uint256(10)**(trustedRSV.decimals()));
// scaleFactor unit: aqTokens/qTokens * qRSV/RSV
uint256 shiftedWeight = amount.mul(weight);
// shiftedWeight unit: qRSV/RSV * aqTokens
// If the weighting is precise, or we're rounding down, then use normal division.
if (rnd == RoundingMode.DOWN || shiftedWeight.mod(scaleFactor) == 0) {
return shiftedWeight.div(scaleFactor);
// return unit: qTokens == qRSV/RSV * aqTokens * (qTokens/aqTokens * RSV/qRSV)
}
return shiftedWeight.div(scaleFactor).add(1); // return unit: qTokens
}
} | Set the Proposal delay in hours. | function setDelay(uint256 _delay) external onlyOwner {
emit DelayChanged(delay, _delay);
delay = _delay;
}
| 12,591,265 | [
1,
694,
326,
19945,
4624,
316,
7507,
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,
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,
444,
6763,
12,
11890,
5034,
389,
10790,
13,
3903,
1338,
5541,
288,
203,
3639,
3626,
20165,
5033,
12,
10790,
16,
389,
10790,
1769,
203,
3639,
4624,
273,
389,
10790,
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
]
|
// SPDX-License-Identifier: MIT
/*
* TheBodega.sol
*
* Created: February 4, 2022
*
* Price: 0.088 ETH
*
* - 535 total supply
* - Pause/unpause minting
* - Limited to 3 mints per wallet
* - Whitelist restricted to Plug hodlers
*/
pragma solidity ^0.8.0;
import "./ERC721A.sol";
import "./access/Pausable.sol";
import "./utils/ReentrancyGuard.sol";
import "./utils/LibPart.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
abstract contract Plug {
function balanceOf(address a) public virtual returns (uint);
}
//@title The Bodega
//@author Jack Kasbeer (git:@jcksber, tw:@satoshigoat, og:overprivilegd)
contract TheBodega is ERC721A, Pausable, ReentrancyGuard {
using SafeMath for uint256;
//@dev Plug instance: mainnet!
Plug constant public thePlug = Plug(0x2Bb501A0374ff3Af41f2009509E9D6a36D56A6c0);
//@dev Supply
uint256 constant MAX_NUM_TOKENS = 545;//number of plug holders
//@dev Properties
string internal _contractURI;
string internal _baseTokenURI;
string internal _tokenHash;
address public payoutAddress;
uint256 public weiPrice;
uint256 constant public royaltyFeeBps = 1500;//15%
bool public openToPublic;
// ---------
// MODIFIERS
// ---------
modifier onlyValidTokenId(uint256 tid) {
require(
0 <= tid && tid < MAX_NUM_TOKENS,
"TheBodega: tid OOB"
);
_;
}
modifier enoughSupply(uint256 qty) {
require(
totalSupply() + qty < MAX_NUM_TOKENS,
"TheBodega: not enough left"
);
_;
}
modifier notEqual(string memory str1, string memory str2) {
require(
!_stringsEqual(str1, str2),
"TheBodega: must be different"
);
_;
}
modifier purchaseArgsOK(address to, uint256 qty, uint256 amount) {
require(
numberMinted(to) + qty <= 3,
"TheBodega: max 3 per wallet"
);
require(
amount >= weiPrice*qty,
"TheBodega: not enough ether"
);
require(
!_isContract(to),
"TheBodega: silly rabbit :P"
);
_;
}
// ------------
// CONSTRUCTION
// ------------
constructor() ERC721A("The Bodega", "") {
_baseTokenURI = "ipfs://";
_tokenHash = "QmbSH67UGGRWNycsNqMBqqnC8ikpriWYM7omqBnSvacm1F";//token metadata ipfs hash
_contractURI = "ipfs://Qmc6XcpjBdU5ZAa1DDFsWG8NyUqW549ejR6WK5XDrwqPUU";
weiPrice = 88000000000000000;//0.088 ETH
payoutAddress = address(0x6b8C6E15818C74895c31A1C91390b3d42B336799);//logik
}
// ----------
// MAIN LOGIC
// ----------
//@dev See {ERC721A16-_baseURI}
function _baseURI() internal view virtual override returns (string memory)
{
return _baseTokenURI;
}
//@dev See {ERC721A16-tokenURI}.
function tokenURI(uint256 tid) public view virtual override
returns (string memory)
{
require(_exists(tid), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(_baseTokenURI, _tokenHash));
}
//@dev Controls the contract-level metadata to include things like royalties
function contractURI() external view returns (string memory)
{
return _contractURI;
}
//@dev Allows owners to mint for free whenever
function mint(address to, uint256 qty)
external isSquad enoughSupply(qty)
{
_safeMint(to, qty);
}
//@dev Allows public addresses (non-owners) to purchase
function plugPurchase(address payable to, uint256 qty)
external payable saleActive enoughSupply(qty) purchaseArgsOK(to, qty, msg.value)
{
require(
thePlug.balanceOf(to) > 0,
"TheBodega: plug hodlers only"
);
_safeMint(to, qty);
}
//@dev Allows public addresses (non-owners) to purchase
function publicPurchase(address payable to, uint256 qty)
external payable saleActive enoughSupply(qty) purchaseArgsOK(to, qty, msg.value)
{
require(
openToPublic,
"TheBodega: sale is not public"
);
_safeMint(to, qty);
}
//@dev Allows us to withdraw funds collected
function withdraw(address payable wallet, uint256 amount)
external isSquad nonReentrant
{
require(
amount <= address(this).balance,
"TheBodega: insufficient funds to withdraw"
);
wallet.transfer(amount);
}
//@dev Destroy contract and reclaim leftover funds
function kill() external onlyOwner
{
selfdestruct(payable(_msgSender()));
}
//@dev See `kill`; protects against being unable to delete a collection on OpenSea
function safe_kill() external onlyOwner
{
require(
balanceOf(_msgSender()) == totalSupply(),
"TheBodega: potential error - not all tokens owned"
);
selfdestruct(payable(_msgSender()));
}
/// -------
/// SETTERS
// --------
//@dev Ability to change the base token URI
function setBaseTokenURI(string calldata newBaseURI)
external isSquad notEqual(_baseTokenURI, newBaseURI) { _baseTokenURI = newBaseURI; }
//@dev Ability to update the token metadata
function setTokenHash(string calldata newHash)
external isSquad notEqual(_tokenHash, newHash) { _tokenHash = newHash; }
//@dev Ability to change the contract URI
function setContractURI(string calldata newContractURI)
external isSquad notEqual(_contractURI, newContractURI) { _contractURI = newContractURI; }
//@dev Change the price
function setPrice(uint256 newWeiPrice) external isSquad
{
require(
weiPrice != newWeiPrice,
"TheBodega: newWeiPrice must be different"
);
weiPrice = newWeiPrice;
}
//@dev Toggle the lock on public purchasing
function toggleOpenToPublic() external isSquad
{
openToPublic = openToPublic ? false : true;
}
// -------
// HELPERS
// -------
//@dev Gives us access to the otw internal function `_numberMinted`
function numberMinted(address owner) public view returns (uint256)
{
return _numberMinted(owner);
}
//@dev Determine if two strings are equal using the length + hash method
function _stringsEqual(string memory a, string memory b)
internal pure returns (bool)
{
bytes memory A = bytes(a);
bytes memory B = bytes(b);
if (A.length != B.length) {
return false;
} else {
return keccak256(A) == keccak256(B);
}
}
//@dev Determine if an address is a smart contract
function _isContract(address a) internal view returns (bool)
{
uint32 size;
assembly {
size := extcodesize(a)
}
return size > 0;
}
// ---------
// ROYALTIES
// ---------
//@dev Rarible Royalties V2
function getRaribleV2Royalties(uint256 tid)
external view onlyValidTokenId(tid)
returns (LibPart.Part[] memory)
{
LibPart.Part[] memory royalties = new LibPart.Part[](1);
royalties[0] = LibPart.Part({
account: payable(payoutAddress),
value: uint96(royaltyFeeBps)
});
return royalties;
}
// @dev See {EIP-2981}
function royaltyInfo(uint256 tid, uint256 salePrice)
external view onlyValidTokenId(tid)
returns (address, uint256)
{
uint256 ourCut = SafeMath.div(SafeMath.mul(salePrice, royaltyFeeBps), 10000);
return (payoutAddress, ourCut);
}
}
// SPDX-License-Identifier: MIT
/*
* ERC721A.sol (by Azuki)
*
* Created: February 4, 2022
*
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721]
* Non-Fungible Token Standard, including the Metadata and Enumerable extension.
* Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint256 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 internal currentIndex;
// 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;
// These are needed for contract compatability
bytes4 internal constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 internal constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 internal constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 internal constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
bytes4 internal constant _INTERFACE_ID_EIP2981 = 0x2a55205a;
bytes4 internal constant _INTERFACE_ID_ROYALTIES = 0xcad96cca;
constructor(string memory 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');
uint128 numMintedSoFar = uint128(totalSupply());
uint128 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when uint16 i is equal to another uint16 numMintedSoFar.
unchecked {
uint128 i;
for (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 == _INTERFACE_ID_ERC165
|| interfaceId == _INTERFACE_ID_ROYALTIES
|| interfaceId == _INTERFACE_ID_ERC721
|| interfaceId == _INTERFACE_ID_ERC721_METADATA
|| interfaceId == _INTERFACE_ID_ERC721_ENUMERABLE
|| interfaceId == _INTERFACE_ID_EIP2981
|| super.supportsInterface(interfaceId);
}
/**
* @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 _addressData[owner].balance;
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), 'ERC721A: number minted query for the zero address');
return _addressData[owner].numberMinted;
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
require(_exists(tokenId), 'ERC721A: owner query for nonexistent token');
unchecked {
uint256 curr;
for (curr = tokenId; curr >= 0; 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[uint16(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 Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement
* {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), 'ERC721A: mint to the zero address');
require(quantity != 0, 'ERC721A: quantity must be greater than 0');
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint128(quantity);
_addressData[to].numberMinted += uint128(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = block.timestamp;
uint256 updatedIndex = startTokenId;
uint256 i;
for (i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
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.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = 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].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = 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 {}
}
// SPDX-License-Identifier: MIT
/*
* Pausable.sol
*
* Created: December 21, 2021
*
* Provides functionality for pausing and unpausing the sale (or other functionality)
*/
pragma solidity >=0.5.16 <0.9.0;
import "./SquadOwnable.sol";
//@title Pausable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract Pausable is SquadOwnable {
event Paused(address indexed a);
event Unpaused(address indexed a);
bool private _paused;
constructor() {
_paused = false;
}
//@dev This will require the sale to be unpaused
modifier saleActive()
{
require(!_paused, "Pausable: sale paused.");
_;
}
//@dev Pause or unpause minting
function toggleSaleActive() external isSquad
{
_paused = !_paused;
if (_paused) {
emit Paused(_msgSender());
} else {
emit Unpaused(_msgSender());
}
}
//@dev Determine if the sale is currently paused
function isPaused() public view virtual returns (bool)
{
return _paused;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
/*
* LibPart.sol
*
* Author: Jack Kasbeer (taken from 'dot')
* Created: October 20, 2021
*/
pragma solidity >=0.5.16 <0.9.0;
//@dev We need this libary for Rarible
library LibPart {
bytes32 public constant TYPE_HASH = keccak256("Part(address account,uint96 value)");
struct Part {
address payable account;
uint96 value;
}
function hash(Part memory part) internal pure returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, part.account, part.value));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
/*
* SquadOwnable.sol
*
* Created: December 21, 2021
*
* An extension of `Ownable.sol` to accomodate for a potential list of owners.
* NOTE: this will need to be the last inherited contract to give all parents
* access to the modifiers it provides
*/
pragma solidity >=0.5.16 <0.9.0;
import "@openzeppelin/contracts/access/Ownable.sol";
//@title SquadOwnable
//@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd)
contract SquadOwnable is Ownable {
//@dev Ownership - list of squad members (owners)
mapping (address => bool) internal _squad;
constructor() {
//add myself and then client
_squad[0xB9699469c0b4dD7B1Dda11dA7678Fa4eFD51211b] = true;
_squad[0x6b8C6E15818C74895c31A1C91390b3d42B336799] = true;//logik
}
//@dev Custom modifier for multiple owners
modifier isSquad()
{
require(isInSquad(_msgSender()), "SquadOwnable: Caller not part of squad.");
_;
}
//@dev Determine if address `a` is an approved owner
function isInSquad(address a) public view returns (bool)
{
return _squad[a];
}
//@dev Add `a` to the squad
function addToSquad(address a) public onlyOwner
{
require(!isInSquad(a), "SquadOwnable: Address already in squad.");
_squad[a] = true;
}
//@dev Remove `a` from the squad
function removeFromSquad(address a) public onlyOwner
{
require(isInSquad(a), "SquadOwnable: Address already not in squad.");
_squad[a] = false;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | SPDX-License-Identifier: MIT Pausable.sol Created: December 21, 2021 Provides functionality for pausing and unpausing the sale (or other functionality)/@title Pausable@author Jack Kasbeer (gh:@jcksber, tw:@satoshigoat, ig:overprivilegd) | contract Pausable is SquadOwnable {
event Paused(address indexed a);
event Unpaused(address indexed a);
bool private _paused;
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
}
pragma solidity >=0.5.16 <0.9.0;
import "./SquadOwnable.sol";
constructor() {
_paused = false;
}
modifier saleActive()
{
require(!_paused, "Pausable: sale paused.");
_;
}
function toggleSaleActive() external isSquad
{
_paused = !_paused;
if (_paused) {
emit Paused(_msgSender());
emit Unpaused(_msgSender());
}
}
function toggleSaleActive() external isSquad
{
_paused = !_paused;
if (_paused) {
emit Paused(_msgSender());
emit Unpaused(_msgSender());
}
}
} else {
function isPaused() public view virtual returns (bool)
{
return _paused;
}
}
| 1,351,700 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
21800,
16665,
18,
18281,
12953,
30,
1505,
311,
81,
744,
9035,
16,
26599,
21,
28805,
14176,
364,
6790,
9940,
471,
640,
8774,
9940,
326,
272,
5349,
261,
280,
1308,
14176,
13176,
21800,
16665,
804,
484,
1475,
345,
2196,
264,
261,
17680,
30,
36,
78,
363,
87,
744,
16,
2339,
30,
36,
12973,
17636,
17626,
270,
16,
18158,
30,
1643,
28459,
19016,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
16351,
21800,
16665,
353,
348,
21733,
5460,
429,
288,
203,
203,
202,
2575,
21800,
3668,
12,
2867,
8808,
279,
1769,
203,
202,
2575,
1351,
8774,
3668,
12,
2867,
8808,
279,
1769,
203,
203,
202,
6430,
3238,
389,
8774,
3668,
31,
203,
203,
565,
445,
389,
5771,
1345,
1429,
18881,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
787,
1345,
548,
16,
203,
3639,
2254,
5034,
10457,
203,
203,
565,
445,
389,
5205,
1345,
1429,
18881,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
787,
1345,
548,
16,
203,
3639,
2254,
5034,
10457,
203,
97,
203,
203,
203,
683,
9454,
18035,
560,
1545,
20,
18,
25,
18,
2313,
411,
20,
18,
29,
18,
20,
31,
203,
203,
5666,
25165,
55,
21733,
5460,
429,
18,
18281,
14432,
203,
203,
202,
12316,
1435,
288,
203,
202,
202,
67,
8774,
3668,
273,
629,
31,
203,
202,
97,
203,
203,
202,
20597,
272,
5349,
3896,
1435,
203,
202,
95,
203,
202,
202,
6528,
12,
5,
67,
8774,
3668,
16,
315,
16507,
16665,
30,
272,
5349,
17781,
1199,
1769,
203,
202,
202,
67,
31,
203,
202,
97,
203,
203,
202,
915,
10486,
30746,
3896,
1435,
3903,
11604,
21733,
203,
202,
95,
203,
202,
202,
67,
8774,
3668,
273,
401,
67,
8774,
3668,
31,
203,
203,
202,
202,
430,
261,
67,
8774,
3668,
13,
288,
203,
1082,
202,
18356,
21800,
3668,
24899,
3576,
12021,
10663,
203,
1082,
202,
18356,
1351,
8774,
3668,
24899,
3576,
12021,
10663,
203,
2
]
|
// Сочетаемость глаголов (и отглагольных частей речи) с предложным
// паттерном.
// 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,485,360 | [
1,
145,
112,
225,
145,
115,
145,
113,
145,
125,
225,
145,
127,
145,
117,
145,
127,
145,
124,
145,
119,
146,
230,
225,
145,
123,
145,
126,
145,
121,
145,
116,
146,
230,
225,
145,
126,
145,
113,
225,
145,
117,
145,
118,
146,
228,
146,
242,
146,
229,
146,
239,
225,
145,
117,
145,
126,
145,
118,
145,
122,
261,
145,
257,
145,
247,
145,
257,
145,
254,
145,
249,
145,
251,
145,
100,
145,
110,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
436,
407,
67,
502,
2038,
30,
145,
257,
145,
247,
145,
257,
145,
254,
145,
249,
145,
251,
145,
100,
145,
110,
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
]
|
pragma solidity ^0.5.2;
import "../ERC20/IERC20.sol";
import "../crowdsale/ICrowdsale.sol";
import "./IPresale.sol";
import "../access/roles/ManagerRole.sol";
import "../access/roles/RecoverRole.sol";
import "../access/roles/FundkeeperRole.sol";
import "../math/SafeMath.sol";
/**
* @title Presale module contract - for tracking records of Presale tokens before claiming at the crowdsale
*
*/
contract Presale is IPresale, ManagerRole, RecoverRole {
using SafeMath for uint256;
/*
* Storage
*/
struct PresaleData {
uint256 allocation;
uint256 balance;
uint256 claimBlock;
}
mapping (address => PresaleData) private _presaleData;
bool private _claimable;
uint256 private _allocation;
uint256 private _totalSupply;
IERC20 private _erc20;
ICrowdsale private _crowdsale;
bool _setCrowdsale;
Stages public stages;
/*
* Enums
*/
enum Stages {
PresaleDeployed,
Presale,
PresaleEnded
}
uint256 CLAIM_PERIOD = 5760; // the number of blocks per claim period (5760 is the number of blocks in a day)
/*
* Modifiers
*/
modifier atStage(Stages _stage) {
require(stages == _stage, "functionality not allowed at current stage");
_;
}
modifier isClaimable() {
require(address(_crowdsale) != address(0x0), "_contract must be deployed and address set");
if (!_claimable){
require(_crowdsale.currentStage() >= 1, "_crowdsale must be initialized to claim");
_claimable = true;
}
_;
}
/**
* @dev Constructor
* @param token TBNERC20 token contract
*/
constructor(IERC20 token) public {
require(address(token) != address(0x0), "token address cannot be 0x0");
_erc20 = token;
stages = Stages.PresaleDeployed;
}
/**
* @dev Safety fallback reverts missent ETH payments
*/
function () external payable {
revert ();
}
/**
* @dev Safety function for recovering missent ERC20 tokens (and recovering the un-distributed allocation after PresaleEnded)
* @param token address of the ERC20 contract to recover
*/
function recoverTokens(IERC20 token)
external
onlyRecoverer
returns (bool)
{
if (token == _erc20){
require(uint(stages) >= 2, "if recovering TBN, must have progressed to PresaleEnded");
}
uint256 recovered = token.balanceOf(address(this));
emit TokensRecovered(token, recovered);
token.transfer(msg.sender, recovered);
return true;
}
/**
* @dev Total number of tokens allocated to presale
*/
function getAllocation() public view returns (uint256) {
return _allocation;
}
/**
* @dev Total number of presale allocated tokens un-distributed to accounts
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Total number of presale tokens distributed to accounts
*/
function getDistribution() public view returns (uint256) {
return _allocation.sub(_totalSupply);
}
/**
* @dev Gets the total presale allocation of the specified address.
* @param account The address to query the balance of.
* @return An uint256 representing the total allocation for this account (claimed or not)
*/
function allocationOf(address account) public view returns (uint256) {
return _presaleData[account].allocation;
}
/**
* @dev Gets the current presale balance of the specified address. (unclaimed tokens)
* @param account The address to query the balance of.
* @return An uint256 representing the amount of presale tokens claimable or transferable
*/
function presaleBalanceOf(address account) public view returns (uint256) {
return _presaleData[account].balance;
}
/**
* @dev Gets the pre-crowdsale presale balance of the specified address.
* @param account The address to query the balance of.
* @return An uint256 representing the last block that this account claimed on
*/
function claimBlock(address account) public view returns (uint256) {
return _presaleData[account].claimBlock;
}
function getERC20() public view returns (address) {
return address(_erc20);
}
function currentStage() public view returns(uint256) {
return uint(stages);
}
/**
* @dev Allows accounts to claim Presale allocated TBN, at a rate of 1% per day accumulated
*/
function claim()
public
isClaimable()
atStage(Stages.Presale)
returns (bool)
{
uint256 claimAmount = _claimAmount(msg.sender);
require(claimAmount > 0, "claimAmount must be greater than 0 to claim - 0 indicates that this account has already claimed this period or has a balance of 0");
emit PresaleClaim(msg.sender, claimAmount);
_erc20.transfer(msg.sender, claimAmount);
return true;
}
/**
* @dev Assigns the presale token allocation to this contract. Note: TBN token fundkeeper must give this contract an allowance before calling initialize
* @param initialAllocation the amount of tokens assigned to this contract for Presale distribution upon initialization
*/
function initilize(uint256 initialAllocation)
external
onlyManager
atStage(Stages.PresaleDeployed)
returns (bool)
{
_addAllocation(initialAllocation);
stages = Stages.Presale;
emit Initialized(initialAllocation);
return true;
}
/**
* @dev Add new presale allocation to the contract. Can only be called by the Manager Role
* @param value The amount of TBN to be added to the total contract allocation
*/
function addAllocation(uint256 value)
external
onlyManager
atStage(Stages.Presale)
returns (bool)
{
_addAllocation(value);
return true;
}
/**
* @dev Assign presale tokens to accounts (only contract Manger and only at presale Stage)
* @param accounts The accounts to add presale token balances to
* @param values The amount of tokens to be added to each account
*/
function addBalance(address[] calldata accounts, uint256[] calldata values)
external
onlyManager
atStage(Stages.Presale)
returns (bool)
{
require(accounts.length == values.length, "presaleAccounts and values must have one-to-one relationship");
for (uint32 i = 0; i < accounts.length; i++) {
_addBalance(accounts[i], values[i]);
}
return true;
}
/**
* @dev Subtract presale tokens to accounts (only contract Manger and only at Presale Stage)
* @param accounts The accounts to subtract presale token balances from
* @param values The amount of tokens to subtract from each account
*/
function subBalance(address[] calldata accounts, uint256[] calldata values)
external
onlyManager
atStage(Stages.Presale)
returns (bool)
{
require(accounts.length == values.length, "accounts and values must have one-to-one relationship");
for (uint32 i = 0; i < accounts.length; i++) {
_subBalance(accounts[i], values[i]);
}
return true;
}
/**
* @dev Transfer presale tokens to another account
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return bool true on success
*/
function presaleTransfer(address from, address to, uint256 value)
external
onlyManager
atStage(Stages.Presale)
returns (bool)
{
_presaleTransfer(from, to, value);
return true;
}
/**
* @dev Called to end presale Stage. Can only be called by the Manager Role. Ends all Manger functionality for record manipulation and ends user claim functionality. Recoverer can recover TBN after this.
*/
function presaleEnd()
external
onlyManager
atStage(Stages.Presale)
returns (bool)
{
stages = Stages.PresaleEnded;
emit PresaleEnded();
return true;
}
/**
* @dev Add allocated TBN to the presale contract (internal operation)
* @param value The amount of tokens to be added to this contract's total allocation
*/
function _addAllocation(uint256 value) internal {
address fundkeeper = FundkeeperRole(address(_erc20)).fundkeeper();
require(_erc20.allowance(address(fundkeeper), address(this)) == value, "presale allocation must be equal to the amount of tokens approved for this contract");
_allocation = _allocation.add(value);
_totalSupply = _totalSupply.add(value);
emit AllocationAdded(value);
// place Presale allocation in this contract (uses the approve/transferFrom pattern)
_erc20.transferFrom(fundkeeper, address(this), value);
}
/**
* @dev Add presale tokens to an account (internal operation)
* @param account The account which is assigned presale holdings
* @param value The amount of tokens to be assigned to this account
*/
function _addBalance(address account, uint256 value) internal {
require(account != address(0), "cannot add balance to the 0x0 account");
require(value <= _totalSupply, "cannot add more allocation to an account than is remaining in the presale supply");
if(_presaleData[account].claimBlock == 0){ // if this account hasn't been allocated tokens before, set the claimBlock to the current block number
_presaleData[account].claimBlock = block.number;
}
_totalSupply = _totalSupply.sub(value);
_presaleData[account].allocation = _presaleData[account].allocation.add(value);
_presaleData[account].balance = _presaleData[account].balance.add(value);
emit BalanceAdded(account, value);
}
/**
* @dev Subtract presale tokens from an account (internal operation)
* @param account The account which is subtracted presale holdings
* @param value The amount of tokens to be assigned to this account
*/
function _subBalance(address account, uint256 value) internal {
require(_presaleData[account].balance > 0, "presaleAccount must have presale balance to subtract");
require(value <= _presaleData[account].balance, "value must be less than or equal to the presale Account balance");
_totalSupply = _totalSupply.add(value);
_presaleData[account].allocation = _presaleData[account].allocation.sub(value);
_presaleData[account].balance = _presaleData[account].balance.sub(value);
emit BalanceSubtracted(account, value);
}
/**
* @dev Transfer presale tokens to another account (internal operation)
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _presaleTransfer(address from, address to, uint256 value) internal {
require(value <= _presaleData[from].balance, "transfer value must be less than the balance of the from account");
require(to != address(0), "cannot transfer to the 0x0 address");
_presaleData[from].allocation = _presaleData[from].allocation.sub(value);
_presaleData[from].balance = _presaleData[from].balance.sub(value);
if(_presaleData[to].claimBlock == 0){ // if the to account hasn't been allocated tokens before, set the claimBlock to the current block number
_presaleData[to].claimBlock = block.number;
}
_presaleData[to].allocation = _presaleData[to].allocation.add(value);
_presaleData[to].balance = _presaleData[to].balance.add(value);
emit Transfer(from, to, value);
}
/**
* @dev Calculates an available claiming portion of an accounts tokens - set to 1% per day accumulated or the remaining balance whichever is smaller (internal operation)
* @param account The account which claiming is calculated for
*/
function _claimAmount(address account) internal returns (uint256) {
uint256 claimAmount;
uint256 intervals;
if(block.number < _presaleData[account].claimBlock.add(CLAIM_PERIOD)) { // check the interval of claiming
return 0; // already claimed this period
} else {
intervals = (block.number.sub(_presaleData[account].claimBlock)).div(CLAIM_PERIOD);
}
if(_presaleData[account].balance <= 10**20){
claimAmount = 10**20; // this is 100 TBN (100 TBN is the minimum claiming amount per interval when balance can support)
} else {
claimAmount = (_presaleData[account].allocation.mul(intervals)).div(100);
if(claimAmount < 10**20) {
claimAmount = 10**20;
}
}
if (_presaleData[account].balance > 0){ // check if there is any remaining balance to claimAmount
if (claimAmount < _presaleData[account].balance) { // check if the claimAmount is < balance
_presaleData[account].balance = _presaleData[account].balance.sub(claimAmount);
_presaleData[account].claimBlock = _presaleData[account].claimBlock.add(CLAIM_PERIOD.mul(intervals));
return claimAmount;
} else { // claimAmount is >= balance
claimAmount = _presaleData[account].balance; // claimAmount all remaining, as the remaining balance is less than this account's approved claim amount
_presaleData[account].balance = _presaleData[account].balance.sub(claimAmount);
_presaleData[account].claimBlock = block.number;
return claimAmount;
}
} else { // no remaining balance to vest
return 0;
}
}
/**
* @dev Set the crowdsale contract storage (only contract Manager and only at Presale Stage)
* @param TBNCrowdsale The crowdsale contract deployment
*/
function setCrowdsale(ICrowdsale TBNCrowdsale)
external
onlyManager
atStage(Stages.Presale)
returns (bool)
{
require(!_setCrowdsale, "the Crowdsale contract address has already been set");
require(TBNCrowdsale.getERC20() == address(_erc20), "Crowdsale contract must be assigned to the same ERC20 instance as this contract");
_crowdsale = TBNCrowdsale;
_setCrowdsale = true;
emit SetCrowdsale(_crowdsale);
return true;
}
} | check the interval of claiming
| if(block.number < _presaleData[account].claimBlock.add(CLAIM_PERIOD)) { | 2,464,430 | [
1,
1893,
326,
3673,
434,
7516,
310,
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,
309,
12,
2629,
18,
2696,
411,
389,
12202,
5349,
751,
63,
4631,
8009,
14784,
1768,
18,
1289,
12,
15961,
3445,
67,
28437,
3719,
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
]
|
./full_match/80001/0x35C94EcA841160336c4b4bd648b55e52034448e1/sources/contracts/Contract.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 to implement supply mechanisms]. We have followed general OpenZeppelin Contracts guidelines: functions revert instead returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./ | contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(
address account
) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(
address owner,
address spender
) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(
address spender,
uint256 amount
) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"ERC20: transfer amount exceeds allowance"
);
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(
currentAllowance >= amount,
"ERC20: transfer amount exceeds allowance"
);
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
function increaseAllowance(
address spender,
uint256 addedValue
) public virtual returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender] + addedValue
);
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function decreaseAllowance(
address spender,
uint256 subtractedValue
) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(
currentAllowance >= subtractedValue,
"ERC20: decreased allowance below zero"
);
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(
senderBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(
senderBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
) internal virtual {}
) internal virtual {}
}
| 873,000 | [
1,
13621,
434,
326,
288,
45,
654,
39,
3462,
97,
1560,
18,
1220,
4471,
353,
279,
1600,
669,
335,
358,
326,
4031,
2430,
854,
2522,
18,
1220,
4696,
716,
279,
14467,
12860,
711,
358,
506,
3096,
316,
279,
10379,
6835,
1450,
288,
67,
81,
474,
5496,
2457,
279,
5210,
12860,
2621,
288,
654,
39,
3462,
18385,
49,
2761,
16507,
1355,
5496,
399,
2579,
30,
2457,
279,
6864,
1045,
416,
2621,
3134,
7343,
358,
2348,
14467,
1791,
28757,
8009,
1660,
1240,
10860,
7470,
3502,
62,
881,
84,
292,
267,
30131,
9875,
14567,
30,
4186,
15226,
3560,
5785,
1375,
5743,
68,
603,
5166,
18,
1220,
6885,
353,
1661,
546,
12617,
15797,
287,
471,
1552,
486,
7546,
598,
326,
26305,
434,
4232,
39,
3462,
12165,
18,
26775,
16,
392,
288,
23461,
97,
871,
353,
17826,
603,
4097,
358,
288,
13866,
1265,
5496,
1220,
5360,
12165,
358,
23243,
326,
1699,
1359,
364,
777,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
4232,
39,
3462,
353,
1772,
16,
467,
654,
39,
3462,
16,
467,
654,
39,
3462,
2277,
288,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
203,
203,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
529,
31,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
389,
7175,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
6549,
31,
203,
565,
289,
203,
203,
565,
445,
2078,
3088,
1283,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
203,
3639,
1758,
2236,
203,
565,
262,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
70,
26488,
63,
4631,
15533,
203,
565,
289,
203,
2
]
|
pragma solidity ^0.4.25;
// expansion on original contract from dav's stronghands contract
// introducing features:
// Jackpot - 1 in 1000 chance to get jackpot upon losing
// Refund line for loser to get their initial eth back
// eth distribution:
// each game seeds 0.01 eth to buy P3D with
// each game seeds 0.005 eth to the refund line making a minimum payback each 20 games played
// 0.1 eth to play per player each round
// expansion Coded by spielley
// Thank you for playing Spielleys contract creations.
// spielley is not liable for any contract bugs and exploits known or unknown.
contract Slaughter3D {
using SafeMath for uint;
struct Stage {
uint8 numberOfPlayers;
uint256 blocknumber;
bool finalized;
mapping (uint8 => address) slotXplayer;
mapping (address => bool) players;
mapping (uint8 => address) setMN;
}
HourglassInterface constant p3dContract = HourglassInterface(0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe);
SPASMInterface constant SPASM_ = SPASMInterface(0xfaAe60F2CE6491886C9f7C9356bd92F688cA66a1);//spielley's profit sharing payout
//a small part of every winners share of the sacrificed players offer is used to purchase p3d instead
uint256 constant private P3D_SHARE = 0.005 ether;
uint8 constant public MAX_PLAYERS_PER_STAGE = 2;
uint256 constant public OFFER_SIZE = 0.1 ether;
uint256 public Refundpot;
uint256 public Jackpot;// 1% of P3D divs to be allocated to the Jackpot
uint256 public SPASMfee;//1% of P3D divs to be shared with SPASM holders
mapping(address => uint256) public ETHtoP3Dbymasternode; //eth to buy P3D masternode
uint256 private p3dPerStage = P3D_SHARE * (MAX_PLAYERS_PER_STAGE - 1);
//not sacrificed players receive their offer back and also a share of the sacrificed players offer
uint256 public winningsPerRound = 0.185 ether;
mapping(address => string) public Vanity;
mapping(address => uint256) private playerVault;
mapping(uint256 => Stage) public stages;
mapping(uint256 => address) public RefundWaitingLine;
mapping(uint256 => address) public Loser;
uint256 public NextInLine;//next person to be refunded
uint256 public NextAtLineEnd;//next spot to add loser
uint256 private numberOfFinalizedStages;
uint256 public numberOfStages;
event JackpotWon(address indexed winner, uint256 SizeOfJackpot);
event SacrificeOffered(address indexed player);
event SacrificeChosen(address indexed sarifice);
event EarningsWithdrawn(address indexed player, uint256 indexed amount);
event StageInvalidated(uint256 indexed stage);
// UI view functions
function previousstagedata()
public
view
returns(address , address , string ,address , string )
{
return (Loser[numberOfFinalizedStages],stages[numberOfFinalizedStages].slotXplayer[0],Vanity[stages[numberOfFinalizedStages].slotXplayer[0]],stages[numberOfFinalizedStages].slotXplayer[1],Vanity[stages[numberOfFinalizedStages].slotXplayer[1]]);
}
function currentstagedata()
public
view
returns( address , string ,address , string )
{
return (stages[numberOfStages].slotXplayer[0],Vanity[stages[numberOfStages].slotXplayer[0]],stages[numberOfStages].slotXplayer[1],Vanity[stages[numberOfStages].slotXplayer[1]]);
}
function jackpotinfo()
public
view
returns(uint256 SizeOfJackpot )
{
return (Jackpot);
}
function checkstatus()// true = ready to vallidate
public
view
returns(bool )
{
bool check;
if(numberOfStages >= numberOfFinalizedStages)
{
if(!stages[numberOfFinalizedStages].finalized && stages[numberOfFinalizedStages].numberOfPlayers < MAX_PLAYERS_PER_STAGE && stages[numberOfFinalizedStages].blocknumber != 0)
{
check = true;
}
}
return (check);
}
function Refundlineinfo()
public
view
returns(address , uint256 ,uint256 , uint256 , string )
{
uint256 LengthUnpaidLine = NextAtLineEnd - NextInLine;
uint256 dividends = p3dContract.myDividends(true);
return (RefundWaitingLine[NextInLine],LengthUnpaidLine, dividends , Refundpot ,Vanity[RefundWaitingLine[NextInLine]]);
}
// expansion functions
// Buy P3D by masternode
function Expand(address masternode) public
{
uint256 amt = ETHtoP3Dbymasternode[masternode];
ETHtoP3Dbymasternode[masternode] = 0;
if(masternode == 0x0){masternode = 0x989eB9629225B8C06997eF0577CC08535fD789F9;}// raffle3d's address
p3dContract.buy.value(amt)(masternode);
}
//fetch P3D divs
function DivsToRefundpot ()public
{
//allocate p3d dividends to contract
uint256 dividends = p3dContract.myDividends(true);
require(dividends > 0);
uint256 base = dividends.div(100);
p3dContract.withdraw();
SPASM_.disburse.value(base)();// to dev fee sharing contract SPASM
Refundpot = Refundpot.add(base.mul(94));
Jackpot = Jackpot.add(base.mul(5)); // allocation to jackpot
//
}
//Donate to losers
function DonateToLosers ()public payable
{
require(msg.value > 0);
Refundpot = Refundpot.add(msg.value);
}
// next loser payout
function Payoutnextrefund ()public
{
//allocate p3d dividends to sacrifice if existing
uint256 Pot = Refundpot;
require(Pot > 0.1 ether);
Refundpot -= 0.1 ether;
RefundWaitingLine[NextInLine].transfer(0.1 ether);
NextInLine++;
//
}
//changevanity
function changevanity(string van , address masternode) public payable
{
require(msg.value >= 1 finney);
Vanity[msg.sender] = van;
uint256 amt = ETHtoP3Dbymasternode[masternode].add(msg.value);
ETHtoP3Dbymasternode[masternode] = 0;
if(masternode == 0x0){masternode = 0x989eB9629225B8C06997eF0577CC08535fD789F9;}// raffle3d's address
p3dContract.buy.value(amt)(masternode);
}
// Sac dep
modifier isValidOffer()
{
require(msg.value == OFFER_SIZE);
_;
}
modifier canPayFromVault()
{
require(playerVault[msg.sender] >= OFFER_SIZE);
_;
}
modifier hasEarnings()
{
require(playerVault[msg.sender] > 0);
_;
}
modifier prepareStage()
{
//create a new stage if current has reached max amount of players
if(stages[numberOfStages - 1].numberOfPlayers == MAX_PLAYERS_PER_STAGE) {
stages[numberOfStages] = Stage(0, 0, false );
numberOfStages++;
}
_;
}
modifier isNewToStage()
{
require(stages[numberOfStages - 1].players[msg.sender] == false);
_;
}
constructor()
public
{
stages[numberOfStages] = Stage(0, 0, false);
numberOfStages++;
}
function() external payable {}
function offerAsSacrifice(address MN)
external
payable
isValidOffer
prepareStage
isNewToStage
{
acceptOffer(MN);
//try to choose a sacrifice in an already full stage (finalize a stage)
tryFinalizeStage();
}
function offerAsSacrificeFromVault(address MN)
external
canPayFromVault
prepareStage
isNewToStage
{
playerVault[msg.sender] -= OFFER_SIZE;
acceptOffer(MN);
tryFinalizeStage();
}
function withdraw()
external
hasEarnings
{
tryFinalizeStage();
uint256 amount = playerVault[msg.sender];
playerVault[msg.sender] = 0;
emit EarningsWithdrawn(msg.sender, amount);
msg.sender.transfer(amount);
}
function myEarnings()
external
view
hasEarnings
returns(uint256)
{
return playerVault[msg.sender];
}
function currentPlayers()
external
view
returns(uint256)
{
return stages[numberOfStages - 1].numberOfPlayers;
}
function acceptOffer(address MN)
private
{
Stage storage currentStage = stages[numberOfStages - 1];
assert(currentStage.numberOfPlayers < MAX_PLAYERS_PER_STAGE);
address player = msg.sender;
//add player to current stage
currentStage.slotXplayer[currentStage.numberOfPlayers] = player;
currentStage.numberOfPlayers++;
currentStage.players[player] = true;
currentStage.setMN[currentStage.numberOfPlayers] = MN;
emit SacrificeOffered(player);
//add blocknumber to current stage when the last player is added
if(currentStage.numberOfPlayers == MAX_PLAYERS_PER_STAGE) {
currentStage.blocknumber = block.number;
}
}
function tryFinalizeStage()
public
{
assert(numberOfStages >= numberOfFinalizedStages);
//there are no stages to finalize
if(numberOfStages == numberOfFinalizedStages) {return;}
Stage storage stageToFinalize = stages[numberOfFinalizedStages];
assert(!stageToFinalize.finalized);
//stage is not ready to be finalized
if(stageToFinalize.numberOfPlayers < MAX_PLAYERS_PER_STAGE) {return;}
assert(stageToFinalize.blocknumber != 0);
//check if blockhash can be determined
if(block.number - 256 <= stageToFinalize.blocknumber) {
//blocknumber of stage can not be equal to current block number -> blockhash() won't work
if(block.number == stageToFinalize.blocknumber) {return;}
//determine sacrifice
uint8 sacrificeSlot = uint8(blockhash(stageToFinalize.blocknumber)) % MAX_PLAYERS_PER_STAGE;
uint256 jackpot = uint256(blockhash(stageToFinalize.blocknumber)) % 1000;
address sacrifice = stageToFinalize.slotXplayer[sacrificeSlot];
Loser[numberOfFinalizedStages] = sacrifice;
emit SacrificeChosen(sacrifice);
//allocate winnings to survivors
allocateSurvivorWinnings(sacrifice);
//check jackpot win
if(jackpot == 777){
sacrifice.transfer(Jackpot);
emit JackpotWon ( sacrifice, Jackpot);
Jackpot = 0;
}
//add sacrifice to refund waiting line
RefundWaitingLine[NextAtLineEnd] = sacrifice;
NextAtLineEnd++;
//set eth to MN for buying P3D
ETHtoP3Dbymasternode[stageToFinalize.setMN[1]] = ETHtoP3Dbymasternode[stageToFinalize.setMN[1]].add(0.005 ether);
ETHtoP3Dbymasternode[stageToFinalize.setMN[1]] = ETHtoP3Dbymasternode[stageToFinalize.setMN[2]].add(0.005 ether);
//add 0.005 ether to Refundpot
Refundpot = Refundpot.add(0.005 ether);
//purchase p3d (using ref) deprecated
//p3dContract.buy.value(p3dPerStage)(address(0x1EB2acB92624DA2e601EEb77e2508b32E49012ef));
} else {
invalidateStage(numberOfFinalizedStages);
emit StageInvalidated(numberOfFinalizedStages);
}
//finalize stage
stageToFinalize.finalized = true;
numberOfFinalizedStages++;
}
function allocateSurvivorWinnings(address sacrifice)
private
{
for (uint8 i = 0; i < MAX_PLAYERS_PER_STAGE; i++) {
address survivor = stages[numberOfFinalizedStages].slotXplayer[i];
if(survivor != sacrifice) {
playerVault[survivor] += winningsPerRound;
}
}
}
function invalidateStage(uint256 stageIndex)
private
{
Stage storage stageToInvalidate = stages[stageIndex];
for (uint8 i = 0; i < MAX_PLAYERS_PER_STAGE; i++) {
address player = stageToInvalidate.slotXplayer[i];
playerVault[player] += OFFER_SIZE;
}
}
}
interface HourglassInterface {
function buy(address _playerAddress) payable external returns(uint256);
function withdraw() external;
function myDividends(bool _includeReferralBonus) external view returns(uint256);
function balanceOf(address _playerAddress) external view returns(uint256);
}
interface SPASMInterface {
function() payable external;
function disburse() external payable;
}
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(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;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
} | a small part of every winners share of the sacrificed players offer is used to purchase p3d instead | uint256 constant private P3D_SHARE = 0.005 ether;
| 10,618,421 | [
1,
69,
5264,
1087,
434,
3614,
5657,
9646,
7433,
434,
326,
20071,
86,
704,
3263,
18115,
10067,
353,
1399,
358,
23701,
293,
23,
72,
3560,
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,
565,
2254,
5034,
5381,
3238,
453,
23,
40,
67,
8325,
862,
273,
374,
18,
28564,
225,
2437,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2019-12-22
*/
pragma solidity ^0.4.14;
pragma experimental ABIEncoderV2;
contract PublicMessage{
string message;
address sender;
function PublicMessage(string _message, address _sender){
message = _message;
sender=_sender;
}
function get_message() returns (string){
return message;
}
function get_message_sender() returns (address){
return sender;
}
}
contract PrivateMessage{
string public encrypted_message;
address public alice;
address public bob;
string public bob_public;
uint256 public stage;
bool public bob_finalized;
bool public bob_error;
event NewPrivateMessage(address PrivateMessage, address alice, address bob);
function PrivateMessage(address _alice, address _bob){ // initiated by alice
//privte messages are initialized by alice along side bob's address and her one time address she created
require(stage==0);
require(msg.sender != _bob);
stage=1;
bob=_bob;
alice = _alice;
emit NewPrivateMessage(address(this), alice, bob);
}
event NewBobReply(address PrivateMessage,address alice, address bob, string bob_public);
function bob_reply(string _bob_public) public{
require(stage==1);
stage=2;
require(tx.origin == bob);
bob_public=_bob_public;
emit NewBobReply(address(this),alice, bob, bob_public);
}
event NewAliceSendEncryptedMessage(address PrivateMessage, address alice, address bob, string bob_public, string encrypted_message);
function alice_send_encrypted_message (string _encrypted_message) public{
require(stage==2);
stage=3;
require(tx.origin == alice);
encrypted_message=_encrypted_message;
emit NewAliceSendEncryptedMessage(address(this), alice, bob, bob_public,encrypted_message);
}
event NewBobFinal(address PrivateMessage, address alice, address bob, bool bob_error);
function bob_final(bool _error) public{
require(stage==3);
stage=4;
require(tx.origin == bob);
bob_finalized=true;
bob_error=_error;
emit NewBobFinal(address(this), alice, bob, bob_error);
}
}
contract Message{
string message;
address sender;
address recipient;
function Message(string _message, address _sender, address _recipient ){
message = _message;
sender=_sender;
recipient=_recipient;
}
function get_message() returns (string){
return message;
}
function get_message_sender() returns (address){
return sender;
}
function get_message_recipient() returns (address){
return recipient;
}
}
contract Txtrs {
struct Txtr {
bytes32 name; // short name (up to 32 bytes)
address owner;
address[] all_sent_messages;
address[] all_received_messages;
address[] all_public_messages;
bool exists;
}
mapping(address => Txtr) public txtrs;
address[] txtrs_list;
address[] public_messages;
uint256 public_messages_length;
//todo function for changing ownership of a username
//todo have Txtr be erc721 token
event NewPublicMessage(address message_addr, string message, address indexed _from);
event NewTxtr(address indexed _from);
//private message events:
event NewPrivateMessage(address PrivateMessage, address alice, address bob);
event NewBobReply2(address PrivateMessage,address alice, address bob, string bob_public);
event NewAliceSendEncryptedMessage(address PrivateMessage, address alice, address bob, string bob_public, string encrypted_message);
event NewBobFinal(address PrivateMessage, address alice, address bob, bool bob_error);
function pm_init(address bob ) returns (address){
address alice = msg.sender;
address message = address( new PrivateMessage ({_alice:alice,_bob:bob}));
if(!txtrs[alice].exists){
create_txtr_on_receive(alice);
}
txtrs[alice].all_sent_messages.push(message);
if(!txtrs[bob].exists){
create_txtr_on_receive(bob);
}
txtrs[bob].all_received_messages.push(message);
emit NewPrivateMessage(message, alice, bob);
return message;
}
function pm_bob_reply(address pm,string bob_public){
PrivateMessage my_pm = PrivateMessage(pm);
my_pm.bob_reply(bob_public);
emit NewBobReply2(pm,my_pm.alice(), my_pm.bob(),bob_public);
}
function pm_alice_send_encrypted_message(address pm, string _encrypted_message){
PrivateMessage my_pm = PrivateMessage(pm);
my_pm.alice_send_encrypted_message(_encrypted_message);
emit NewAliceSendEncryptedMessage(pm, my_pm.alice(), my_pm.bob(),my_pm.bob_public(), _encrypted_message);
}
function pm_bob_final(address pm, bool _error){
PrivateMessage my_pm = PrivateMessage(pm);
my_pm.bob_final(_error);
emit NewBobFinal(pm, my_pm.alice(), my_pm.bob(), _error);
}
function send_public_message(string message_text) returns (address){
address message = address(new PublicMessage({_message:message_text, _sender:msg.sender }));
if(!txtrs[msg.sender].exists){
txtrs[msg.sender]=create_txtr_on_receive(msg.sender);
emit NewTxtr(msg.sender);
}
txtrs[msg.sender].all_public_messages.push(message);
public_messages.push(message);
public_messages_length+=1;
emit NewPublicMessage(message, message_text,msg.sender);
return message;
}
function get_public_message_count() returns (uint256){
return public_messages.length;
}
function get_public_message_address(uint256 index) returns (address){
return public_messages[index];
}
function get_public_message_message(uint256 index) returns (string){
address addr = public_messages[index];
PublicMessage message = PublicMessage(addr);
return message.get_message();
}
function get_public_message_sender(uint256 index) returns (address){
address addr = public_messages[index];
PublicMessage message = PublicMessage(addr);
return message.get_message_sender();
}
function create_txtr_on_public_message(address addr) private returns (Txtr){
address[] storage all_sent_messages;
address[] storage all_received_messages;
address[] storage all_public_messages;
txtrs_list.push(addr);
return Txtr({name:'', owner:addr, all_sent_messages: all_sent_messages,all_received_messages:all_received_messages,all_public_messages:all_public_messages,exists:true });
}
function create_txtr_on_receive(address addr) private returns (Txtr){
address[] storage all_sent_messages;
address[] storage all_received_messages;
address[] storage all_public_messages;
txtrs_list.push(addr);
return Txtr({name:'', owner:addr, all_sent_messages: all_sent_messages,all_received_messages:all_received_messages,all_public_messages:all_public_messages,exists:true });
}
function create_txtr(bytes32 username) {
address[] storage all_sent_messages;
address[] storage all_received_messages;
address[] storage all_public_messages;
txtrs[msg.sender] = Txtr({name:username, owner:msg.sender, all_sent_messages: all_sent_messages,all_received_messages:all_received_messages,all_public_messages:all_public_messages,exists:true });
txtrs_list.push(msg.sender);
}
function create_message(string message_text, address recipient) returns (address){
address message = address(new Message({_message:message_text, _sender:msg.sender, _recipient:recipient }));
if(!txtrs[msg.sender].exists){
txtrs[msg.sender]=create_txtr_on_receive(msg.sender);
}
txtrs[msg.sender].all_sent_messages.push(message);
if(!txtrs[recipient].exists){
txtrs[recipient]=create_txtr_on_receive(recipient);
}
txtrs[recipient].all_received_messages.push(message);
return message;
}
function get_received_messages_total(address addr) public returns (uint256) {
return txtrs[addr].all_received_messages.length;
}
function get_received_message(address addr, uint256 index) public returns (address) {
return address(txtrs[addr].all_received_messages[index]);
}
function get_sent_messages_total(address addr) public returns (uint256) {
return txtrs[addr].all_sent_messages.length;
}
function get_sent_message(address addr, uint256 index) public returns (address) {
return address(txtrs[addr].all_sent_messages[index]);
}
function get_one_message(uint256 index, address addr) public returns (string) {
address _msg = txtrs[addr].all_received_messages[index];
Message message = Message(_msg);
return message.get_message();
}
function get_one_message_sender(uint256 index, address addr) public returns (address) {
address _msg = txtrs[addr].all_received_messages[index];
Message message = Message(_msg);
return message.get_message_sender();
}
function get_one_message_recipient(uint256 index, address addr) public returns (address) {
address _msg = txtrs[addr].all_received_messages[index];
Message message = Message(_msg);
return message.get_message_recipient();
}
function get_sent_user_message_total(address addr) public returns (uint256) {
return txtrs[addr].all_sent_messages.length;
}
function get_one_sent_message(uint256 index, address addr) public returns (string) {
address _msg = txtrs[addr].all_sent_messages[index];
Message message = Message(_msg);
return message.get_message();
}
}
| privte messages are initialized by alice along side bob's address and her one time address she created | contract PrivateMessage{
string public encrypted_message;
address public alice;
address public bob;
string public bob_public;
uint256 public stage;
bool public bob_finalized;
bool public bob_error;
event NewPrivateMessage(address PrivateMessage, address alice, address bob);
require(stage==0);
require(msg.sender != _bob);
stage=1;
bob=_bob;
alice = _alice;
emit NewPrivateMessage(address(this), alice, bob);
}
| 13,132,051 | [
1,
11365,
736,
2743,
854,
6454,
635,
524,
1812,
7563,
4889,
800,
70,
1807,
1758,
471,
22336,
1245,
813,
1758,
23901,
2522,
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,
16351,
8726,
1079,
95,
203,
203,
565,
533,
1071,
6901,
67,
2150,
31,
203,
565,
1758,
1071,
524,
1812,
31,
203,
565,
1758,
1071,
800,
70,
31,
203,
565,
533,
1071,
800,
70,
67,
482,
31,
203,
565,
2254,
5034,
1071,
6009,
31,
203,
203,
565,
1426,
1071,
800,
70,
67,
6385,
1235,
31,
203,
565,
1426,
1071,
800,
70,
67,
1636,
31,
203,
203,
565,
871,
1166,
6014,
1079,
12,
2867,
8726,
1079,
16,
1758,
524,
1812,
16,
1758,
800,
70,
1769,
7010,
3639,
2583,
12,
12869,
631,
20,
1769,
203,
3639,
2583,
12,
3576,
18,
15330,
480,
389,
70,
947,
1769,
203,
3639,
6009,
33,
21,
31,
203,
3639,
800,
70,
33,
67,
70,
947,
31,
203,
3639,
524,
1812,
273,
389,
287,
1812,
31,
203,
3639,
3626,
1166,
6014,
1079,
12,
2867,
12,
2211,
3631,
524,
1812,
16,
800,
70,
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
]
|
/*
* Origin Protocol
* https://originprotocol.com
*
* Released under the MIT license
* https://github.com/OriginProtocol/origin-dollar
*
* Copyright 2020 Origin Protocol, Inc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.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 ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: contracts/interfaces/IStrategy.sol
pragma solidity 0.5.11;
/**
* @title Platform interface to integrate with lending platform like Compound, AAVE etc.
*/
interface IStrategy {
/**
* @dev Deposit the given asset to platform
* @param _asset asset address
* @param _amount Amount to deposit
*/
function deposit(address _asset, uint256 _amount) external;
/**
* @dev Deposit the entire balance of all supported assets in the Strategy
* to the platform
*/
function depositAll() external;
/**
* @dev Withdraw given asset from Lending platform
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external;
/**
* @dev Liquidate all assets in strategy and return them to Vault.
*/
function withdrawAll() external;
/**
* @dev Returns the current balance of the given asset.
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Returns bool indicating whether strategy supports asset.
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Collect reward tokens from the Strategy.
*/
function collectRewardToken() external;
/**
* @dev The address of the reward token for the Strategy.
*/
function rewardTokenAddress() external pure returns (address);
/**
* @dev The threshold (denominated in the reward token) over which the
* vault will auto harvest on allocate calls.
*/
function rewardLiquidationThreshold() external pure returns (uint256);
}
// File: contracts/governance/Governable.sol
pragma solidity 0.5.11;
/**
* @title OUSD Governable Contract
* @dev Copy of the openzeppelin Ownable.sol contract with nomenclature change
* from owner to governor and renounce methods removed. Does not use
* Context.sol like Ownable.sol does for simplification.
* @author Origin Protocol Inc
*/
contract Governable {
// Storage position of the owner and pendingOwner of the contract
// keccak256("OUSD.governor");
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
// keccak256("OUSD.pending.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
// keccak256("OUSD.reentry.status");
bytes32
private constant reentryStatusPosition = 0x53bf423e48ed90e97d02ab0ebab13b2a235a6bfbe9c321847d5c175333ac4535;
// See OpenZeppelin ReentrancyGuard implementation
uint256 constant _NOT_ENTERED = 1;
uint256 constant _ENTERED = 2;
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
/**
* @dev Returns the address of the current Governor.
*/
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
/**
* @dev Returns the address of the pending Governor.
*/
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @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() {
bytes32 position = reentryStatusPosition;
uint256 _reentry_status;
assembly {
_reentry_status := sload(position)
}
// On the first call to nonReentrant, _notEntered will be true
require(_reentry_status != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
assembly {
sstore(position, _ENTERED)
}
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly {
sstore(position, _NOT_ENTERED)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
// File: contracts/utils/InitializableERC20Detailed.sol
pragma solidity 0.5.11;
/**
* @dev Optional functions from the ERC20 standard.
* Converted from openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
*/
contract InitializableERC20Detailed is IERC20 {
// Storage gap to skip storage from prior to OUSD reset
uint256[100] private _____gap;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
* @notice To avoid variable shadowing appended `Arg` after arguments name.
*/
function _initialize(
string memory nameArg,
string memory symbolArg,
uint8 decimalsArg
) internal {
_name = nameArg;
_symbol = symbolArg;
_decimals = decimalsArg;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/utils/StableMath.sol
pragma solidity 0.5.11;
// Based on StableMath from Stability Labs Pty. Ltd.
// https://github.com/mstable/mStable-contracts/blob/master/contracts/shared/StableMath.sol
library StableMath {
using SafeMath for uint256;
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/***************************************
Helpers
****************************************/
/**
* @dev Adjust the scale of an integer
* @param adjustment Amount to adjust by e.g. scaleBy(1e18, -1) == 1e17
*/
function scaleBy(uint256 x, int8 adjustment)
internal
pure
returns (uint256)
{
if (adjustment > 0) {
x = x.mul(10**uint256(adjustment));
} else if (adjustment < 0) {
x = x.div(10**uint256(adjustment * -1));
}
return x;
}
/***************************************
Precise Arithmetic
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
uint256 z = x.mul(y);
// return 9e38 / 1e18 = 9e18
return z.div(scale);
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x.mul(y);
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled.add(FULL_SCALE.sub(1));
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil.div(FULL_SCALE);
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
// e.g. 8e18 * 1e18 = 8e36
uint256 z = x.mul(FULL_SCALE);
// e.g. 8e36 / 10e18 = 8e17
return z.div(y);
}
}
// File: contracts/token/OUSD.sol
pragma solidity 0.5.11;
/**
* @title OUSD Token Contract
* @dev ERC20 compatible contract for OUSD
* @dev Implements an elastic supply
* @author Origin Protocol Inc
*/
/**
* NOTE that this is an ERC20 token but the invariant that the sum of
* balanceOf(x) for all x is not >= totalSupply(). This is a consequence of the
* rebasing design. Any integrations with OUSD should be aware.
*/
contract OUSD is Initializable, InitializableERC20Detailed, Governable {
using SafeMath for uint256;
using StableMath for uint256;
event TotalSupplyUpdated(
uint256 totalSupply,
uint256 rebasingCredits,
uint256 rebasingCreditsPerToken
);
enum RebaseOptions { NotSet, OptOut, OptIn }
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 public _totalSupply;
mapping(address => mapping(address => uint256)) private _allowances;
address public vaultAddress = address(0);
mapping(address => uint256) private _creditBalances;
uint256 public rebasingCredits;
uint256 public rebasingCreditsPerToken;
// Frozen address/credits are non rebasing (value is held in contracts which
// do not receive yield unless they explicitly opt in)
uint256 public nonRebasingSupply;
mapping(address => uint256) public nonRebasingCreditsPerToken;
mapping(address => RebaseOptions) public rebaseState;
function initialize(
string calldata _nameArg,
string calldata _symbolArg,
address _vaultAddress
) external onlyGovernor initializer {
InitializableERC20Detailed._initialize(_nameArg, _symbolArg, 18);
rebasingCreditsPerToken = 1e18;
vaultAddress = _vaultAddress;
}
/**
* @dev Verifies that the caller is the Savings Manager contract
*/
modifier onlyVault() {
require(vaultAddress == msg.sender, "Caller is not the Vault");
_;
}
/**
* @return The total supply of OUSD.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param _account Address to query the balance of.
* @return A uint256 representing the _amount of base units owned by the
* specified address.
*/
function balanceOf(address _account) public view returns (uint256) {
if (_creditBalances[_account] == 0) return 0;
return
_creditBalances[_account].divPrecisely(_creditsPerToken(_account));
}
/**
* @dev Gets the credits balance of the specified address.
* @param _account The address to query the balance of.
* @return (uint256, uint256) Credit balance and credits per token of the
* address
*/
function creditsBalanceOf(address _account)
public
view
returns (uint256, uint256)
{
return (_creditBalances[_account], _creditsPerToken(_account));
}
/**
* @dev Transfer tokens to a specified address.
* @param _to the address to transfer to.
* @param _value the _amount to be transferred.
* @return true on success.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(
_value <= balanceOf(msg.sender),
"Transfer greater than balance"
);
_executeTransfer(msg.sender, _to, _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value The _amount of tokens to be transferred.
*/
function transferFrom(
address _from,
address _to,
uint256 _value
) public returns (bool) {
require(_to != address(0), "Transfer to zero address");
require(_value <= balanceOf(_from), "Transfer greater than balance");
_allowances[_from][msg.sender] = _allowances[_from][msg.sender].sub(
_value
);
_executeTransfer(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Update the count of non rebasing credits in response to a transfer
* @param _from The address you want to send tokens from.
* @param _to The address you want to transfer to.
* @param _value Amount of OUSD to transfer
*/
function _executeTransfer(
address _from,
address _to,
uint256 _value
) internal {
bool isNonRebasingTo = _isNonRebasingAccount(_to);
bool isNonRebasingFrom = _isNonRebasingAccount(_from);
// Credits deducted and credited might be different due to the
// differing creditsPerToken used by each account
uint256 creditsCredited = _value.mulTruncate(_creditsPerToken(_to));
uint256 creditsDeducted = _value.mulTruncate(_creditsPerToken(_from));
_creditBalances[_from] = _creditBalances[_from].sub(
creditsDeducted,
"Transfer amount exceeds balance"
);
_creditBalances[_to] = _creditBalances[_to].add(creditsCredited);
if (isNonRebasingTo && !isNonRebasingFrom) {
// Transfer to non-rebasing account from rebasing account, credits
// are removed from the non rebasing tally
nonRebasingSupply = nonRebasingSupply.add(_value);
// Update rebasingCredits by subtracting the deducted amount
rebasingCredits = rebasingCredits.sub(creditsDeducted);
} else if (!isNonRebasingTo && isNonRebasingFrom) {
// Transfer to rebasing account from non-rebasing account
// Decreasing non-rebasing credits by the amount that was sent
nonRebasingSupply = nonRebasingSupply.sub(_value);
// Update rebasingCredits by adding the credited amount
rebasingCredits = rebasingCredits.add(creditsCredited);
}
}
/**
* @dev Function to check the _amount of tokens that an owner has allowed to a _spender.
* @param _owner The address which owns the funds.
* @param _spender The address which will spend the funds.
* @return The number of tokens still available for the _spender.
*/
function allowance(address _owner, address _spender)
public
view
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @dev Approve the passed address to spend the specified _amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param _spender The address which will spend the funds.
* @param _value The _amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
_allowances[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the _amount of tokens that an owner has allowed to a _spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param _spender The address which will spend the funds.
* @param _addedValue The _amount of tokens to increase the allowance by.
*/
function increaseAllowance(address _spender, uint256 _addedValue)
public
returns (bool)
{
_allowances[msg.sender][_spender] = _allowances[msg.sender][_spender]
.add(_addedValue);
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the _amount of tokens that an owner has allowed to a _spender.
* @param _spender The address which will spend the funds.
* @param _subtractedValue The _amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue)
public
returns (bool)
{
uint256 oldValue = _allowances[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
_allowances[msg.sender][_spender] = 0;
} else {
_allowances[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, _allowances[msg.sender][_spender]);
return true;
}
/**
* @dev Mints new tokens, increasing totalSupply.
*/
function mint(address _account, uint256 _amount) external onlyVault {
_mint(_account, _amount);
}
/**
* @dev Creates `_amount` tokens and assigns them to `_account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address _account, uint256 _amount) internal nonReentrant {
require(_account != address(0), "Mint to the zero address");
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
_creditBalances[_account] = _creditBalances[_account].add(creditAmount);
// If the account is non rebasing and doesn't have a set creditsPerToken
// then set it i.e. this is a mint from a fresh contract
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.add(_amount);
} else {
rebasingCredits = rebasingCredits.add(creditAmount);
}
_totalSupply = _totalSupply.add(_amount);
require(_totalSupply < MAX_SUPPLY, "Max supply");
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Burns tokens, decreasing totalSupply.
*/
function burn(address account, uint256 amount) external onlyVault {
_burn(account, amount);
}
/**
* @dev Destroys `_amount` tokens from `_account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `_account` cannot be the zero address.
* - `_account` must have at least `_amount` tokens.
*/
function _burn(address _account, uint256 _amount) internal nonReentrant {
require(_account != address(0), "Burn from the zero address");
if (_amount == 0) {
return;
}
bool isNonRebasingAccount = _isNonRebasingAccount(_account);
uint256 creditAmount = _amount.mulTruncate(_creditsPerToken(_account));
uint256 currentCredits = _creditBalances[_account];
// Remove the credits, burning rounding errors
if (
currentCredits == creditAmount || currentCredits - 1 == creditAmount
) {
// Handle dust from rounding
_creditBalances[_account] = 0;
} else if (currentCredits > creditAmount) {
_creditBalances[_account] = _creditBalances[_account].sub(
creditAmount
);
} else {
revert("Remove exceeds balance");
}
// Remove from the credit tallies and non-rebasing supply
if (isNonRebasingAccount) {
nonRebasingSupply = nonRebasingSupply.sub(_amount);
} else {
rebasingCredits = rebasingCredits.sub(creditAmount);
}
_totalSupply = _totalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Get the credits per token for an account. Returns a fixed amount
* if the account is non-rebasing.
* @param _account Address of the account.
*/
function _creditsPerToken(address _account)
internal
view
returns (uint256)
{
if (nonRebasingCreditsPerToken[_account] != 0) {
return nonRebasingCreditsPerToken[_account];
} else {
return rebasingCreditsPerToken;
}
}
/**
* @dev Is an account using rebasing accounting or non-rebasing accounting?
* Also, ensure contracts are non-rebasing if they have not opted in.
* @param _account Address of the account.
*/
function _isNonRebasingAccount(address _account) internal returns (bool) {
bool isContract = Address.isContract(_account);
if (isContract && rebaseState[_account] == RebaseOptions.NotSet) {
_ensureRebasingMigration(_account);
}
return nonRebasingCreditsPerToken[_account] > 0;
}
/**
* @dev Ensures internal account for rebasing and non-rebasing credits and
* supply is updated following deployment of frozen yield change.
*/
function _ensureRebasingMigration(address _account) internal {
if (nonRebasingCreditsPerToken[_account] == 0) {
// Set fixed credits per token for this account
nonRebasingCreditsPerToken[_account] = rebasingCreditsPerToken;
// Update non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(_account));
// Update credit tallies
rebasingCredits = rebasingCredits.sub(_creditBalances[_account]);
}
}
/**
* @dev Add a contract address to the non rebasing exception list. I.e. the
* address's balance will be part of rebases so the account will be exposed
* to upside and downside.
*/
function rebaseOptIn() public nonReentrant {
require(_isNonRebasingAccount(msg.sender), "Account has not opted out");
// Convert balance into the same amount at the current exchange rate
uint256 newCreditBalance = _creditBalances[msg.sender]
.mul(rebasingCreditsPerToken)
.div(_creditsPerToken(msg.sender));
// Decreasing non rebasing supply
nonRebasingSupply = nonRebasingSupply.sub(balanceOf(msg.sender));
_creditBalances[msg.sender] = newCreditBalance;
// Increase rebasing credits, totalSupply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.add(_creditBalances[msg.sender]);
rebaseState[msg.sender] = RebaseOptions.OptIn;
// Delete any fixed credits per token
delete nonRebasingCreditsPerToken[msg.sender];
}
/**
* @dev Remove a contract address to the non rebasing exception list.
*/
function rebaseOptOut() public nonReentrant {
require(!_isNonRebasingAccount(msg.sender), "Account has not opted in");
// Increase non rebasing supply
nonRebasingSupply = nonRebasingSupply.add(balanceOf(msg.sender));
// Set fixed credits per token
nonRebasingCreditsPerToken[msg.sender] = rebasingCreditsPerToken;
// Decrease rebasing credits, total supply remains unchanged so no
// adjustment necessary
rebasingCredits = rebasingCredits.sub(_creditBalances[msg.sender]);
// Mark explicitly opted out of rebasing
rebaseState[msg.sender] = RebaseOptions.OptOut;
}
/**
* @dev Modify the supply without minting new tokens. This uses a change in
* the exchange rate between "credits" and OUSD tokens to change balances.
* @param _newTotalSupply New total supply of OUSD.
* @return uint256 representing the new total supply.
*/
function changeSupply(uint256 _newTotalSupply)
external
onlyVault
nonReentrant
{
require(_totalSupply > 0, "Cannot increase 0 supply");
if (_totalSupply == _newTotalSupply) {
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
return;
}
_totalSupply = _newTotalSupply > MAX_SUPPLY
? MAX_SUPPLY
: _newTotalSupply;
rebasingCreditsPerToken = rebasingCredits.divPrecisely(
_totalSupply.sub(nonRebasingSupply)
);
require(rebasingCreditsPerToken > 0, "Invalid change in supply");
_totalSupply = rebasingCredits
.divPrecisely(rebasingCreditsPerToken)
.add(nonRebasingSupply);
emit TotalSupplyUpdated(
_totalSupply,
rebasingCredits,
rebasingCreditsPerToken
);
}
}
// File: contracts/interfaces/IBasicToken.sol
pragma solidity 0.5.11;
interface IBasicToken {
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// File: contracts/utils/Helpers.sol
pragma solidity 0.5.11;
library Helpers {
/**
* @notice Fetch the `symbol()` from an ERC20 token
* @dev Grabs the `symbol()` from a contract
* @param _token Address of the ERC20 token
* @return string Symbol of the ERC20 token
*/
function getSymbol(address _token) internal view returns (string memory) {
string memory symbol = IBasicToken(_token).symbol();
return symbol;
}
/**
* @notice Fetch the `decimals()` from an ERC20 token
* @dev Grabs the `decimals()` from a contract and fails if
* the decimal value does not live within a certain range
* @param _token Address of the ERC20 token
* @return uint256 Decimals of the ERC20 token
*/
function getDecimals(address _token) internal view returns (uint256) {
uint256 decimals = IBasicToken(_token).decimals();
require(
decimals >= 4 && decimals <= 18,
"Token must have sufficient decimal places"
);
return decimals;
}
}
// File: contracts/vault/VaultStorage.sol
pragma solidity 0.5.11;
/**
* @title OUSD VaultStorage Contract
* @notice The VaultStorage contract defines the storage for the Vault contracts
* @author Origin Protocol Inc
*/
contract VaultStorage is Initializable, Governable {
using SafeMath for uint256;
using StableMath for uint256;
using SafeMath for int256;
using SafeERC20 for IERC20;
event AssetSupported(address _asset);
event AssetDefaultStrategyUpdated(address _asset, address _strategy);
event StrategyApproved(address _addr);
event StrategyRemoved(address _addr);
event Mint(address _addr, uint256 _value);
event Redeem(address _addr, uint256 _value);
event CapitalPaused();
event CapitalUnpaused();
event RebasePaused();
event RebaseUnpaused();
event VaultBufferUpdated(uint256 _vaultBuffer);
event RedeemFeeUpdated(uint256 _redeemFeeBps);
event PriceProviderUpdated(address _priceProvider);
event AllocateThresholdUpdated(uint256 _threshold);
event RebaseThresholdUpdated(uint256 _threshold);
event UniswapUpdated(address _address);
event StrategistUpdated(address _address);
event MaxSupplyDiffChanged(uint256 maxSupplyDiff);
event YieldDistribution(address _to, uint256 _yield, uint256 _fee);
event TrusteeFeeBpsChanged(uint256 _basis);
event TrusteeAddressChanged(address _address);
// Assets supported by the Vault, i.e. Stablecoins
struct Asset {
bool isSupported;
}
mapping(address => Asset) assets;
address[] allAssets;
// Strategies approved for use by the Vault
struct Strategy {
bool isSupported;
uint256 _deprecated; // Deprecated storage slot
}
mapping(address => Strategy) strategies;
address[] allStrategies;
// Address of the Oracle price provider contract
address public priceProvider;
// Pausing bools
bool public rebasePaused = false;
bool public capitalPaused = true;
// Redemption fee in basis points
uint256 public redeemFeeBps;
// Buffer of assets to keep in Vault to handle (most) withdrawals
uint256 public vaultBuffer;
// Mints over this amount automatically allocate funds. 18 decimals.
uint256 public autoAllocateThreshold;
// Mints over this amount automatically rebase. 18 decimals.
uint256 public rebaseThreshold;
OUSD oUSD;
//keccak256("OUSD.vault.governor.admin.impl");
bytes32 constant adminImplPosition = 0xa2bd3d3cf188a41358c8b401076eb59066b09dec5775650c0de4c55187d17bd9;
// Address of the contract responsible for post rebase syncs with AMMs
address private _deprecated_rebaseHooksAddr = address(0);
// Address of Uniswap
address public uniswapAddr = address(0);
// Address of the Strategist
address public strategistAddr = address(0);
// Mapping of asset address to the Strategy that they should automatically
// be allocated to
mapping(address => address) public assetDefaultStrategies;
uint256 public maxSupplyDiff;
// Trustee address that can collect a percentage of yield
address public trusteeAddress;
// Amount of yield collected in basis points
uint256 public trusteeFeeBps;
/**
* @dev set the implementation for the admin, this needs to be in a base class else we cannot set it
* @param newImpl address of the implementation
*/
function setAdminImpl(address newImpl) external onlyGovernor {
require(
Address.isContract(newImpl),
"new implementation is not a contract"
);
bytes32 position = adminImplPosition;
assembly {
sstore(position, newImpl)
}
}
}
// File: contracts/interfaces/IMinMaxOracle.sol
pragma solidity 0.5.11;
interface IMinMaxOracle {
//Assuming 8 decimals
function priceMin(string calldata symbol) external view returns (uint256);
function priceMax(string calldata symbol) external view returns (uint256);
}
// File: contracts/interfaces/uniswap/IUniswapV2Router02.sol
pragma solidity 0.5.11;
interface IUniswapV2Router {
function WETH() external pure returns (address);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
}
// File: contracts/vault/VaultAdmin.sol
pragma solidity 0.5.11;
/**
* @title OUSD Vault Admin Contract
* @notice The VaultAdmin contract makes configuration and admin calls on the vault.
* @author Origin Protocol Inc
*/
contract VaultAdmin is VaultStorage {
/**
* @dev Verifies that the caller is the Vault, Governor, or Strategist.
*/
modifier onlyVaultOrGovernorOrStrategist() {
require(
msg.sender == address(this) ||
msg.sender == strategistAddr ||
isGovernor(),
"Caller is not the Vault, Governor, or Strategist"
);
_;
}
modifier onlyGovernorOrStrategist() {
require(
msg.sender == strategistAddr || isGovernor(),
"Caller is not the Strategist or Governor"
);
_;
}
/***************************************
Configuration
****************************************/
/**
* @dev Set address of price provider.
* @param _priceProvider Address of price provider
*/
function setPriceProvider(address _priceProvider) external onlyGovernor {
priceProvider = _priceProvider;
emit PriceProviderUpdated(_priceProvider);
}
/**
* @dev Set a fee in basis points to be charged for a redeem.
* @param _redeemFeeBps Basis point fee to be charged
*/
function setRedeemFeeBps(uint256 _redeemFeeBps) external onlyGovernor {
redeemFeeBps = _redeemFeeBps;
emit RedeemFeeUpdated(_redeemFeeBps);
}
/**
* @dev Set a buffer of assets to keep in the Vault to handle most
* redemptions without needing to spend gas unwinding assets from a Strategy.
* @param _vaultBuffer Percentage using 18 decimals. 100% = 1e18.
*/
function setVaultBuffer(uint256 _vaultBuffer) external onlyGovernor {
require(_vaultBuffer <= 1e18, "Invalid value");
vaultBuffer = _vaultBuffer;
emit VaultBufferUpdated(_vaultBuffer);
}
/**
* @dev Sets the minimum amount of OUSD in a mint to trigger an
* automatic allocation of funds afterwords.
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setAutoAllocateThreshold(uint256 _threshold)
external
onlyGovernor
{
autoAllocateThreshold = _threshold;
emit AllocateThresholdUpdated(_threshold);
}
/**
* @dev Set a minimum amount of OUSD in a mint or redeem that triggers a
* rebase
* @param _threshold OUSD amount with 18 fixed decimals.
*/
function setRebaseThreshold(uint256 _threshold) external onlyGovernor {
rebaseThreshold = _threshold;
emit RebaseThresholdUpdated(_threshold);
}
/**
* @dev Set address of Uniswap for performing liquidation of strategy reward
* tokens
* @param _address Address of Uniswap
*/
function setUniswapAddr(address _address) external onlyGovernor {
uniswapAddr = _address;
emit UniswapUpdated(_address);
}
/**
* @dev Set address of Strategist
* @param _address Address of Strategist
*/
function setStrategistAddr(address _address) external onlyGovernor {
strategistAddr = _address;
emit StrategistUpdated(_address);
}
/**
* @dev Set the default Strategy for an asset, i.e. the one which the asset
will be automatically allocated to and withdrawn from
* @param _asset Address of the asset
* @param _strategy Address of the Strategy
*/
function setAssetDefaultStrategy(address _asset, address _strategy)
external
onlyGovernorOrStrategist
{
emit AssetDefaultStrategyUpdated(_asset, _strategy);
require(strategies[_strategy].isSupported, "Strategy not approved");
IStrategy strategy = IStrategy(_strategy);
require(assets[_asset].isSupported, "Asset is not supported");
require(
strategy.supportsAsset(_asset),
"Asset not supported by Strategy"
);
assetDefaultStrategies[_asset] = _strategy;
}
/**
* @dev Add a supported asset to the contract, i.e. one that can be
* to mint OUSD.
* @param _asset Address of asset
*/
function supportAsset(address _asset) external onlyGovernor {
require(!assets[_asset].isSupported, "Asset already supported");
assets[_asset] = Asset({ isSupported: true });
allAssets.push(_asset);
emit AssetSupported(_asset);
}
/**
* @dev Add a strategy to the Vault.
* @param _addr Address of the strategy to add
*/
function approveStrategy(address _addr) external onlyGovernor {
require(!strategies[_addr].isSupported, "Strategy already approved");
strategies[_addr] = Strategy({ isSupported: true, _deprecated: 0 });
allStrategies.push(_addr);
emit StrategyApproved(_addr);
}
/**
* @dev Remove a strategy from the Vault. Removes all invested assets and
* returns them to the Vault.
* @param _addr Address of the strategy to remove
*/
function removeStrategy(address _addr) external onlyGovernor {
require(strategies[_addr].isSupported, "Strategy not approved");
// Initialize strategyIndex with out of bounds result so function will
// revert if no valid index found
uint256 strategyIndex = allStrategies.length;
for (uint256 i = 0; i < allStrategies.length; i++) {
if (allStrategies[i] == _addr) {
strategyIndex = i;
break;
}
}
if (strategyIndex < allStrategies.length) {
allStrategies[strategyIndex] = allStrategies[allStrategies.length -
1];
allStrategies.pop();
// Withdraw all assets
IStrategy strategy = IStrategy(_addr);
strategy.withdrawAll();
// Call harvest after withdraw in case withdraw triggers
// distribution of additional reward tokens (true for Compound)
_harvest(_addr);
emit StrategyRemoved(_addr);
}
// Clean up struct in mapping, this can be removed later
// See https://github.com/OriginProtocol/origin-dollar/issues/324
strategies[_addr].isSupported = false;
}
/**
* @notice Move assets from one Strategy to another
* @param _strategyFromAddress Address of Strategy to move assets from.
* @param _strategyToAddress Address of Strategy to move assets to.
* @param _assets Array of asset address that will be moved
* @param _amounts Array of amounts of each corresponding asset to move.
*/
function reallocate(
address _strategyFromAddress,
address _strategyToAddress,
address[] calldata _assets,
uint256[] calldata _amounts
) external onlyGovernorOrStrategist {
require(
strategies[_strategyFromAddress].isSupported,
"Invalid from Strategy"
);
require(
strategies[_strategyToAddress].isSupported,
"Invalid to Strategy"
);
require(_assets.length == _amounts.length, "Parameter length mismatch");
IStrategy strategyFrom = IStrategy(_strategyFromAddress);
IStrategy strategyTo = IStrategy(_strategyToAddress);
for (uint256 i = 0; i < _assets.length; i++) {
require(strategyTo.supportsAsset(_assets[i]), "Asset unsupported");
// Withdraw from Strategy and pass other Strategy as recipient
strategyFrom.withdraw(address(strategyTo), _assets[i], _amounts[i]);
}
// Tell new Strategy to deposit into protocol
strategyTo.depositAll();
}
/**
* @dev Sets the maximum allowable difference between
* total supply and backing assets' value.
*/
function setMaxSupplyDiff(uint256 _maxSupplyDiff) external onlyGovernor {
maxSupplyDiff = _maxSupplyDiff;
emit MaxSupplyDiffChanged(_maxSupplyDiff);
}
/**
* @dev Sets the trusteeAddress that can receive a portion of yield.
* Setting to the zero address disables this feature.
*/
function setTrusteeAddress(address _address) external onlyGovernor {
trusteeAddress = _address;
emit TrusteeAddressChanged(_address);
}
/**
* @dev Sets the TrusteeFeeBps to the percentage of yield that should be
* received in basis points.
*/
function setTrusteeFeeBps(uint256 _basis) external onlyGovernor {
require(_basis <= 5000, "basis cannot exceed 50%");
trusteeFeeBps = _basis;
emit TrusteeFeeBpsChanged(_basis);
}
/***************************************
Pause
****************************************/
/**
* @dev Set the deposit paused flag to true to prevent rebasing.
*/
function pauseRebase() external onlyGovernorOrStrategist {
rebasePaused = true;
emit RebasePaused();
}
/**
* @dev Set the deposit paused flag to true to allow rebasing.
*/
function unpauseRebase() external onlyGovernor {
rebasePaused = false;
emit RebaseUnpaused();
}
/**
* @dev Set the deposit paused flag to true to prevent capital movement.
*/
function pauseCapital() external onlyGovernorOrStrategist {
capitalPaused = true;
emit CapitalPaused();
}
/**
* @dev Set the deposit paused flag to false to enable capital movement.
*/
function unpauseCapital() external onlyGovernor {
capitalPaused = false;
emit CapitalUnpaused();
}
/***************************************
Rewards
****************************************/
/**
* @dev Transfer token to governor. Intended for recovering tokens stuck in
* contract, i.e. mistaken sends.
* @param _asset Address for the asset
* @param _amount Amount of the asset to transfer
*/
function transferToken(address _asset, uint256 _amount)
external
onlyGovernor
{
require(!assets[_asset].isSupported, "Only unsupported assets");
IERC20(_asset).safeTransfer(governor(), _amount);
}
/**
* @dev Collect reward tokens from all strategies and swap for supported
* stablecoin via Uniswap
*/
function harvest() external onlyGovernorOrStrategist {
for (uint256 i = 0; i < allStrategies.length; i++) {
_harvest(allStrategies[i]);
}
}
/**
* @dev Collect reward tokens for a specific strategy and swap for supported
* stablecoin via Uniswap. Called from the vault.
* @param _strategyAddr Address of the strategy to collect rewards from
*/
function harvest(address _strategyAddr)
external
onlyVaultOrGovernorOrStrategist
returns (uint256[] memory)
{
return _harvest(_strategyAddr);
}
/**
* @dev Collect reward tokens from a single strategy and swap them for a
* supported stablecoin via Uniswap
* @param _strategyAddr Address of the strategy to collect rewards from
*/
function _harvest(address _strategyAddr)
internal
returns (uint256[] memory)
{
IStrategy strategy = IStrategy(_strategyAddr);
address rewardTokenAddress = strategy.rewardTokenAddress();
if (rewardTokenAddress != address(0)) {
strategy.collectRewardToken();
if (uniswapAddr != address(0)) {
IERC20 rewardToken = IERC20(strategy.rewardTokenAddress());
uint256 rewardTokenAmount = rewardToken.balanceOf(
address(this)
);
if (rewardTokenAmount > 0) {
// Give Uniswap full amount allowance
rewardToken.safeApprove(uniswapAddr, 0);
rewardToken.safeApprove(uniswapAddr, rewardTokenAmount);
// Uniswap redemption path
address[] memory path = new address[](3);
path[0] = strategy.rewardTokenAddress();
path[1] = IUniswapV2Router(uniswapAddr).WETH();
path[2] = allAssets[1]; // USDT
return
IUniswapV2Router(uniswapAddr).swapExactTokensForTokens(
rewardTokenAmount,
uint256(0),
path,
address(this),
now.add(1800)
);
}
}
}
}
/***************************************
Pricing
****************************************/
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Min since min is what we use for mint pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function priceUSDMint(string calldata symbol)
external
view
returns (uint256)
{
return _priceUSDMint(symbol);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Min since min is what we use for mint pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function _priceUSDMint(string memory symbol)
internal
view
returns (uint256)
{
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return IMinMaxOracle(priceProvider).priceMin(symbol).scaleBy(10);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Max since max is what we use for redeem pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function priceUSDRedeem(string calldata symbol)
external
view
returns (uint256)
{
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return _priceUSDRedeem(symbol);
}
/**
* @dev Returns the total price in 18 digit USD for a given asset.
* Using Max since max is what we use for redeem pricing
* @param symbol String symbol of the asset
* @return uint256 USD price of 1 of the asset
*/
function _priceUSDRedeem(string memory symbol)
internal
view
returns (uint256)
{
// Price from Oracle is returned with 8 decimals
// scale to 18 so 18-8=10
return IMinMaxOracle(priceProvider).priceMax(symbol).scaleBy(10);
}
}
| Deprecated storage slot
| uint256 _deprecated; | 483,444 | [
1,
13534,
2502,
4694,
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,
3639,
2254,
5034,
389,
14089,
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.6 <0.6.0;
/// @title Shared constants used throughout the Cheeze Wizards contracts
contract WizardConstants {
// Wizards normally have their affinity set when they are first created,
// but for example Exclusive Wizards can be created with no set affinity.
// In this case the affinity can be set by the owner.
uint8 internal constant ELEMENT_NOTSET = 0; //000
// A neutral Wizard has no particular strength or weakness with specific
// elements.
uint8 internal constant ELEMENT_NEUTRAL = 1; //001
// The fire, water and wind elements are used both to reflect an affinity
// of Elemental Wizards for a specific element, and as the moves a
// Wizard can make during a duel.
// Note thta if these values change then `moveMask` and `moveDelta` in
// ThreeAffinityDuelResolver would need to be updated accordingly.
uint8 internal constant ELEMENT_FIRE = 2; //010
uint8 internal constant ELEMENT_WATER = 3; //011
uint8 internal constant ELEMENT_WIND = 4; //100
uint8 internal constant MAX_ELEMENT = ELEMENT_WIND;
}
/// @title ERC165Query example
/// @notice see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
contract ERC165Query {
bytes4 public constant _INTERFACE_ID_INVALID = 0xffffffff;
bytes4 public constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
function doesContractImplementInterface(
address _contract,
bytes4 _interfaceId
)
public
view
returns (bool)
{
uint256 success;
uint256 result;
(success, result) = noThrowCall(_contract, _INTERFACE_ID_ERC165);
if ((success == 0) || (result == 0)) {
return false;
}
(success, result) = noThrowCall(_contract, _INTERFACE_ID_INVALID);
if ((success == 0) || (result != 0)) {
return false;
}
(success, result) = noThrowCall(_contract, _interfaceId);
if ((success == 1) && (result == 1)) {
return true;
}
return false;
}
function noThrowCall(
address _contract,
bytes4 _interfaceId
)
internal
view
returns (
uint256 success,
uint256 result
)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, _interfaceId);
// solhint-disable-next-line no-inline-assembly
assembly { // solium-disable-line security/no-inline-assembly
let encodedParams_data := add(0x20, encodedParams)
let encodedParams_size := mload(encodedParams)
let output := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(output, 0x0)
success := staticcall(
30000, // 30k gas
_contract, // To addr
encodedParams_data,
encodedParams_size,
output,
0x20 // Outputs are 32 bytes long
)
result := mload(output) // Load the result
}
}
}
/**
* @title IERC165
* @dev https://eips.ethereum.org/EIPS/eip-165
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function transferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId) public;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 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 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
/// @title ERC165Interface
/// @dev https://eips.ethereum.org/EIPS/eip-165
interface ERC165Interface {
/// @notice Query if a contract implements an interface
/// @param interfaceId The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/// Utility library of inline functions on address payables.
/// Modified from original by OpenZeppelin.
contract Address {
/// @notice 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 account address of the account to check
/// @return whether the target address is a contract
function isContract(address account) 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.
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
/// @title Wizard Non-Fungible Token
/// @notice The basic ERC-721 functionality for storing Cheeze Wizard NFTs.
/// Derived from: https://github.com/OpenZeppelin/openzeppelin-solidity/tree/v2.2.0
contract WizardNFT is ERC165Interface, IERC721, WizardConstants, Address {
/// @notice Transfer of a Wizard between different owners.
event Transfer(address from, address to, uint256 wizardId);
/// @notice Approval for another address to transfer a Wizard.
event Approval(address owner, address approved, uint256 wizardId);
/// @notice Approval for another address to transfer all Wizards owned by a single address.
event ApprovalForAll(address owner, address operator, bool approved);
/// @notice Emitted when a wizard token is created.
event WizardConjured(uint256 wizardId, uint8 affinity, uint256 innatePower);
/// @notice Emitted when a Wizard's affinity is set. This only applies for
/// Exclusive Wizards who can have the ELEMENT_NOT_SET affinity,
/// and should only happen once for each Wizard.
event WizardAffinityAssigned(uint256 wizardId, uint8 affinity);
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 internal constant _ERC721_RECEIVED = 0x150b7a02;
/// @dev The base Wizard structure.
/// Designed to fit in two words.
struct Wizard {
// NOTE: Changing the order or meaning of any of these fields requires an update
// to the _createWizard() function which assumes a specific order for these fields.
uint8 affinity;
uint88 innatePower;
address owner;
bytes32 metadata;
}
// Mapping from Wizard ID to Wizard struct
mapping (uint256 => Wizard) public wizardsById;
// Mapping from Wizard ID to address approved to control them
mapping (uint256 => address) private wizardApprovals;
// Mapping from owner address to number of owned Wizards
mapping (address => uint256) internal ownedWizardsCount;
// Mapping from owner to Wizard controllers
mapping (address => mapping (address => bool)) private _operatorApprovals;
/// @dev 0x80ac58cd ===
/// bytes4(keccak256('balanceOf(address)')) ^
/// bytes4(keccak256('ownerOf(uint256)')) ^
/// bytes4(keccak256('approve(address,uint256)')) ^
/// bytes4(keccak256('getApproved(uint256)')) ^
/// bytes4(keccak256('setApprovalForAll(address,bool)')) ^
/// bytes4(keccak256('isApprovedForAll(address,address)')) ^
/// bytes4(keccak256('transferFrom(address,address,uint256)')) ^
/// bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
/// bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/// @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) public view returns (bool) {
return
interfaceId == this.supportsInterface.selector || // ERC165
interfaceId == _INTERFACE_ID_ERC721; // ERC721
}
/// @notice Gets the number of Wizards owned by the specified address.
/// @param owner Address to query the balance of.
/// @return uint256 representing the amount of Wizards owned by the address.
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return ownedWizardsCount[owner];
}
/// @notice Gets the owner of the specified Wizard
/// @param wizardId ID of the Wizard to query the owner of
/// @return address currently marked as the owner of the given Wizard
function ownerOf(uint256 wizardId) public view returns (address) {
address owner = wizardsById[wizardId].owner;
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/// @notice Approves another address to transfer the given Wizard
/// The zero address indicates there is no approved address.
/// There can only be one approved address per Wizard at a given time.
/// Can only be called by the Wizard owner or an approved operator.
/// @param to address to be approved for the given Wizard
/// @param wizardId ID of the Wizard to be approved
function approve(address to, uint256 wizardId) public {
address owner = ownerOf(wizardId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
wizardApprovals[wizardId] = to;
emit Approval(owner, to, wizardId);
}
/// @notice Gets the approved address for a Wizard, or zero if no address set
/// Reverts if the Wizard does not exist.
/// @param wizardId ID of the Wizard to query the approval of
/// @return address currently approved for the given Wizard
function getApproved(uint256 wizardId) public view returns (address) {
require(_exists(wizardId), "ERC721: approved query for nonexistent token");
return wizardApprovals[wizardId];
}
/// @notice Sets or unsets the approval of a given operator.
/// An operator is allowed to transfer all Wizards 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, "ERC721: approve to caller");
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/// @notice 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];
}
/// @notice Transfers the ownership of a given Wizard 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 Wizard.
/// @param to address to receive the ownership of the given Wizard.
/// @param wizardId ID of the Wizard to be transferred.
function transferFrom(address from, address to, uint256 wizardId) public {
require(_isApprovedOrOwner(msg.sender, wizardId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, wizardId);
}
/// @notice Safely transfers the ownership of a given Wizard 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 Wizard.
/// @param to address to receive the ownership of the given Wizard.
/// @param wizardId ID of the Wizard to be transferred.
function safeTransferFrom(address from, address to, uint256 wizardId) public {
safeTransferFrom(from, to, wizardId, "");
}
/// @notice Safely transfers the ownership of a given Wizard 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 Wizard.
/// @param to address to receive the ownership of the given Wizard.
/// @param wizardId ID of the Wizard to be transferred.
/// @param _data bytes data to send along with a safe transfer check
function safeTransferFrom(address from, address to, uint256 wizardId, bytes memory _data) public {
transferFrom(from, to, wizardId);
require(_checkOnERC721Received(from, to, wizardId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/// @notice Returns whether the specified Wizard exists.
/// @param wizardId ID of the Wizard to query the existence of..
/// @return bool whether the Wizard exists.
function _exists(uint256 wizardId) internal view returns (bool) {
address owner = wizardsById[wizardId].owner;
return owner != address(0);
}
/// @notice Returns whether the given spender can transfer a given Wizard.
/// @param spender address of the spender to query
/// @param wizardId ID of the Wizard to be transferred
/// @return bool whether the msg.sender is approved for the given Wizard,
/// is an operator of the owner, or is the owner of the Wizard.
function _isApprovedOrOwner(address spender, uint256 wizardId) internal view returns (bool) {
require(_exists(wizardId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(wizardId);
return (spender == owner || getApproved(wizardId) == spender || isApprovedForAll(owner, spender));
}
/** @dev Internal function to create a new Wizard; reverts if the Wizard ID is taken.
* NOTE: This function heavily depends on the internal format of the Wizard struct
* and should always be reassessed if anything about that structure changes.
* @param wizardId ID of the new Wizard.
* @param owner The address that will own the newly conjured Wizard.
* @param innatePower The power level associated with the new Wizard.
* @param affinity The elemental affinity of the new Wizard.
*/
function _createWizard(uint256 wizardId, address owner, uint88 innatePower, uint8 affinity) internal {
require(owner != address(0), "ERC721: mint to the zero address");
require(!_exists(wizardId), "ERC721: token already minted");
require(wizardId > 0, "No 0 token allowed");
require(innatePower > 0, "Wizard power must be non-zero");
// Create the Wizard!
wizardsById[wizardId] = Wizard({
affinity: affinity,
innatePower: uint88(innatePower),
owner: owner,
metadata: 0
});
ownedWizardsCount[owner]++;
// Tell the world!
emit Transfer(address(0), owner, wizardId);
emit WizardConjured(wizardId, affinity, innatePower);
}
/// @notice Internal function to burn a specific Wizard.
/// Reverts if the Wizard does not exist.
/// Deprecated, use _burn(uint256) instead.
/// @param owner owner of the Wizard to burn.
/// @param wizardId ID of the Wizard being burned
function _burn(address owner, uint256 wizardId) internal {
require(ownerOf(wizardId) == owner, "ERC721: burn of token that is not own");
_clearApproval(wizardId);
ownedWizardsCount[owner]--;
// delete the entire object to recover the most gas
delete wizardsById[wizardId];
// required for ERC721 compatibility
emit Transfer(owner, address(0), wizardId);
}
/// @notice Internal function to burn a specific Wizard.
/// Reverts if the Wizard does not exist.
/// @param wizardId ID of the Wizard being burned
function _burn(uint256 wizardId) internal {
_burn(ownerOf(wizardId), wizardId);
}
/// @notice Internal function to transfer ownership of a given Wizard to another address.
/// As opposed to transferFrom, this imposes no restrictions on msg.sender.
/// @param from current owner of the Wizard.
/// @param to address to receive the ownership of the given Wizard
/// @param wizardId ID of the Wizard to be transferred
function _transferFrom(address from, address to, uint256 wizardId) internal {
require(ownerOf(wizardId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(wizardId);
ownedWizardsCount[from]--;
ownedWizardsCount[to]++;
wizardsById[wizardId].owner = to;
emit Transfer(from, to, wizardId);
}
/// @notice 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 Wizard
/// @param to target address that will receive the Wizards.
/// @param wizardId ID of the Wizard 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 wizardId, bytes memory _data)
internal returns (bool)
{
if (!isContract(to)) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, wizardId, _data);
return (retval == _ERC721_RECEIVED);
}
/// @notice Private function to clear current approval of a given Wizard.
/// @param wizardId ID of the Wizard to be transferred
function _clearApproval(uint256 wizardId) private {
if (wizardApprovals[wizardId] != address(0)) {
wizardApprovals[wizardId] = address(0);
}
}
}
contract WizardGuildInterfaceId {
bytes4 internal constant _INTERFACE_ID_WIZARDGUILD = 0x41d4d437;
}
/// @title The public interface of the Wizard Guild
/// @notice The methods listed in this interface (including the inherited ERC-721 interface),
/// make up the public interface of the Wizard Guild contract. Any contracts that wish
/// to make use of Cheeze Wizard NFTs (such as Cheeze Wizards Tournaments!) should use
/// these methods to ensure they are working correctly with the base NFTs.
contract WizardGuildInterface is IERC721, WizardGuildInterfaceId {
/// @notice Returns the information associated with the given Wizard
/// owner - The address that owns this Wizard
/// innatePower - The innate power level of this Wizard, set when minted and entirely
/// immutable
/// affinity - The Elemental Affinity of this Wizard. For most Wizards, this is set
/// when they are minted, but some exclusive Wizards are minted with an affinity
/// of 0 (ELEMENT_NOTSET). A Wizard with an NOTSET affinity should NOT be able
/// to participate in Tournaments. Once the affinity of a Wizard is set to a non-zero
/// value, it can never be changed again.
/// metadata - A 256-bit hash of the Wizard's metadata, which is stored off chain. This
/// contract doesn't specify format of this hash, nor the off-chain storage mechanism
/// but, let's be honest, it's probably an IPFS SHA-256 hash.
///
/// NOTE: Series zero Wizards have one of four Affinities: Neutral (1), Fire (2), Water (3)
/// or Air (4, sometimes called "Wind" in the code). Future Wizard Series may have
/// additional Affinities, and clients of this API should be prepared for that
/// eventuality.
function getWizard(uint256 id) external view returns (address owner, uint88 innatePower, uint8 affinity, bytes32 metadata);
/// @notice Sets the affinity for a Wizard that doesn't already have its elemental affinity chosen.
/// Only usable for Exclusive Wizards (all non-Exclusives must have their affinity chosen when
/// conjured.) Even Exclusives can't change their affinity once it's been chosen.
///
/// NOTE: This function can only be called by the series minter, and (therefore) only while the
/// series is open. A Wizard that has no affinity when a series is closed will NEVER have an Affinity.
/// BTW- This implies that a minter is responsible for either never minting ELEMENT_NOTSET
/// Wizards, or having some public mechanism for a Wizard owner to set the Affinity after minting.
/// @param wizardId The id of the wizard
/// @param newAffinity The new affinity of the wizard
function setAffinity(uint256 wizardId, uint8 newAffinity) external;
/// @notice A function to be called that conjures a whole bunch of Wizards at once! You know how
/// there's "a pride of lions", "a murder of crows", and "a parliament of owls"? Well, with this
/// here function you can conjure yourself "a stench of Cheeze Wizards"!
///
/// Unsurprisingly, this method can only be called by the registered minter for a Series.
/// @param powers the power level of each wizard
/// @param affinities the Elements of the wizards to create
/// @param owner the address that will own the newly created Wizards
function mintWizards(
uint88[] calldata powers,
uint8[] calldata affinities,
address owner
) external returns (uint256[] memory wizardIds);
/// @notice A function to be called that conjures a series of Wizards in the reserved ID range.
/// @param wizardIds the ID values to use for each Wizard, must be in the reserved range of the current Series
/// @param affinities the Elements of the wizards to create
/// @param powers the power level of each wizard
/// @param owner the address that will own the newly created Wizards
function mintReservedWizards(
uint256[] calldata wizardIds,
uint88[] calldata powers,
uint8[] calldata affinities,
address owner
) external;
/// @notice Sets the metadata values for a list of Wizards. The metadata for a Wizard can only be set once,
/// can only be set by the COO or Minter, and can only be set while the Series is still open. Once
/// a Series is closed, the metadata is locked forever!
/// @param wizardIds the ID values of the Wizards to apply metadata changes to.
/// @param metadata the raw metadata values for each Wizard. This contract does not define how metadata
/// should be interpreted, but it is likely to be a 256-bit hash of a complete metadata package
/// accessible via IPFS or similar.
function setMetadata(uint256[] calldata wizardIds, bytes32[] calldata metadata) external;
/// @notice Returns true if the given "spender" address is allowed to manipulate the given token
/// (either because it is the owner of that token, has been given approval to manage that token)
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
/// @notice Verifies that a given signature represents authority to control the given Wizard ID,
/// reverting otherwise. It handles three cases:
/// - The simplest case: The signature was signed with the private key associated with
/// an external address that is the owner of this Wizard.
/// - The signature was generated with the private key associated with an external address
/// that is "approved" for working with this Wizard ID. (See the Wizard Guild and/or
/// the ERC-721 spec for more information on "approval".)
/// - The owner or approval address (as in cases one or two) is a smart contract
/// that conforms to ERC-1654, and accepts the given signature as being valid
/// using its own internal logic.
///
/// NOTE: This function DOES NOT accept a signature created by an address that was given "operator
/// status" (as granted by ERC-721's setApprovalForAll() functionality). Doing so is
/// considered an extreme edge case that can be worked around where necessary.
/// @param wizardId The Wizard ID whose control is in question
/// @param hash The message hash we are authenticating against
/// @param sig the signature data; can be longer than 65 bytes for ERC-1654
function verifySignature(uint256 wizardId, bytes32 hash, bytes calldata sig) external view;
/// @notice Convienence function that verifies signatures for two wizards using equivalent logic to
/// verifySignature(). Included to save on cross-contract calls in the common case where we
/// are verifying the signatures of two Wizards who wish to enter into a Duel.
/// @param wizardId1 The first Wizard ID whose control is in question
/// @param wizardId2 The second Wizard ID whose control is in question
/// @param hash1 The message hash we are authenticating against for the first Wizard
/// @param hash2 The message hash we are authenticating against for the first Wizard
/// @param sig1 the signature data corresponding to the first Wizard; can be longer than 65 bytes for ERC-1654
/// @param sig2 the signature data corresponding to the second Wizard; can be longer than 65 bytes for ERC-1654
function verifySignatures(
uint256 wizardId1,
uint256 wizardId2,
bytes32 hash1,
bytes32 hash2,
bytes calldata sig1,
bytes calldata sig2) external view;
}
/// @title Contract that manages addresses and access modifiers for certain operations.
/// @author Dapper Labs Inc. (https://www.dapperlabs.com)
contract AccessControl {
/// @dev The address of the master administrator account that has the power to
/// update itself and all of the other administrator addresses.
/// The CEO account is not expected to be used regularly, and is intended to
/// be stored offline (i.e. a hardware device kept in a safe).
address public ceoAddress;
/// @dev The address of the "day-to-day" operator of various priviledged
/// functions inside the smart contract. Although the CEO has the power
/// to replace the COO, the CEO address doesn't actually have the power
/// to do "COO-only" operations. This is to discourage the regular use
/// of the CEO account.
address public cooAddress;
/// @dev The address that is allowed to move money around. Kept seperate from
/// the COO because the COO address typically lives on an internet-connected
/// computer.
address payable public cfoAddress;
// Events to indicate when access control role addresses are updated.
event CEOTransferred(address previousCeo, address newCeo);
event COOTransferred(address previousCoo, address newCoo);
event CFOTransferred(address previousCfo, address newCfo);
/// @dev The AccessControl constructor sets the `ceoAddress` to the sender account. Also
/// initializes the COO and CFO to the passed values (CFO is optional and can be address(0)).
/// @param newCooAddress The initial COO address to set
/// @param newCfoAddress The initial CFO to set (optional)
constructor(address newCooAddress, address payable newCfoAddress) public {
_setCeo(msg.sender);
setCoo(newCooAddress);
if (newCfoAddress != address(0)) {
setCfo(newCfoAddress);
}
}
/// @notice Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress, "Only CEO");
_;
}
/// @notice Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress, "Only COO");
_;
}
/// @notice Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress, "Only CFO");
_;
}
function checkControlAddress(address newController) internal view {
require(newController != address(0), "Zero access control address");
require(newController != ceoAddress, "CEO address cannot be reused");
}
/// @notice Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param newCeo The address of the new CEO
function setCeo(address newCeo) external onlyCEO {
checkControlAddress(newCeo);
_setCeo(newCeo);
}
/// @dev An internal utility function that updates the CEO variable and emits the
/// transfer event. Used from both the public setCeo function and the constructor.
function _setCeo(address newCeo) private {
emit CEOTransferred(ceoAddress, newCeo);
ceoAddress = newCeo;
}
/// @notice Assigns a new address to act as the COO. Only available to the current CEO.
/// @param newCoo The address of the new COO
function setCoo(address newCoo) public onlyCEO {
checkControlAddress(newCoo);
emit COOTransferred(cooAddress, newCoo);
cooAddress = newCoo;
}
/// @notice Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param newCfo The address of the new CFO
function setCfo(address payable newCfo) public onlyCEO {
checkControlAddress(newCfo);
emit CFOTransferred(cfoAddress, newCfo);
cfoAddress = newCfo;
}
}
/// @title Signature utility library
library SigTools {
/// @notice Splits a signature into r & s values, and v (the verification value).
/// @dev Note: This does not verify the version, but does require signature length = 65
/// @param signature the packed signature to be split
function _splitSignature(bytes memory signature) internal pure returns (bytes32 r, bytes32 s, uint8 v) {
// Check signature length
require(signature.length == 65, "Invalid signature length");
// We need to unpack the signature, which is given as an array of 65 bytes (like eth.sign)
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(signature, 32))
s := mload(add(signature, 64))
v := and(mload(add(signature, 65)), 255)
}
if (v < 27) {
v += 27; // Ethereum versions are 27 or 28 as opposed to 0 or 1 which is submitted by some signing libs
}
// check for valid version
// removed for now, done in another function
//require((v == 27 || v == 28), "Invalid signature version");
return (r, s, v);
}
}
contract ERC1654 {
/// @dev bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 public constant ERC1654_VALIDSIGNATURE = 0x1626ba7e;
/// @dev Should return whether the signature provided is valid for the provided data
/// @param hash 32-byte hash of the data that is signed
/// @param _signature Signature byte array associated with _data
/// MUST return the bytes4 magic value 0x1626ba7e when function passes.
/// MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
/// MUST allow external calls
function isValidSignature(
bytes32 hash,
bytes calldata _signature)
external
view
returns (bytes4);
}
/// @title The master organization behind all Cheeze Wizardry. The source of all them Wiz.
contract WizardGuild is AccessControl, WizardNFT, WizardGuildInterface, ERC165Query {
/// @notice Emitted when a new Series is opened or closed.
event SeriesOpen(uint64 seriesIndex, uint256 reservedIds);
event SeriesClose(uint64 seriesIndex);
/// @notice Emitted when metadata is associated with a Wizard
event MetadataSet(uint256 indexed wizardId, bytes32 metadata);
/// @notice The index of the current Series (zero-based). When no Series is open, this value
/// indicates the index of the _upcoming_ Series. (i.e. it is incremented when the
/// Series is closed. This makes it easier to bootstrap the first Series.)
uint64 internal seriesIndex;
/// @notice The address which is allowed to mint new Wizards in the current Series. When this
/// is set to address(0), there is no open Series.
address internal seriesMinter;
/// @notice The index number of the next Wizard to be created (Neutral or Elemental).
/// NOTE: There is a subtle distinction between a Wizard "ID" and a Wizard "index".
/// We use the term "ID" to refer to a value that includes the Series number in the
/// top 64 bits, while the term "index" refers to the Wizard number _within_ its
/// Series. This is especially confusing when talking about Wizards in the first
/// Series (Series 0), because the two values are identical in that case!
///
/// |---------------|--------------------------|
/// | Wizard ID (256 bits) |
/// |---------------|--------------------------|
/// | Series Index | Wizard Index |
/// | (64 bits) | (192 bits) |
/// |---------------|--------------------------|
uint256 internal nextWizardIndex;
// NOTE: uint256(-1) maps to a value with all bits set, both the << and >> operators will fill
// in with zeros when acting on an unsigned value. So, "uint256(-1) << 192" resovles to "a bunch
/// of ones, followed by 192 zeros"
uint256 internal constant seriesOffset = 192;
uint256 internal constant seriesMask = uint256(-1) << seriesOffset;
uint256 internal constant indexMask = uint256(-1) >> 64;
// The ERC1654 function selector value
bytes4 internal constant ERC1654_VALIDSIGNATURE = 0x1626ba7e;
/// @notice The Guild constructor.
/// @param _cooAddress The COO has the ability to create new Series and to update
/// the metadata on the currently open Series (if any). It has no other special
/// abilities, and (in particular), ALL Wizards in a closed series can never be
/// modified or deleted. If the CEO and COO values are ever set to invalid addresses
/// (such as address(1)), then no new Series can ever be created, either.
constructor(address _cooAddress) public AccessControl(_cooAddress, address(0)) {
}
/// @notice Require that a Tournament Series is currently open. For example closing
/// a Series does not make sense if none is open.
/// @dev While in other contracts we use separate checking functions to avoid having the same
/// string inlined in multiple places, given this modifier is scarcely used it doesn't seem
/// worth the per-call gas cost here.
modifier duringSeries() {
require(seriesMinter != address(0), "No series is currently open");
_;
}
/// @notice Require that the caller is the minter of the current series. This implicitely
/// requires that a Series is open, or the minter address would be invalid (can never
/// be matched).
/// @dev While in other contracts we use separate checking functions to avoid having the same
/// string inlined in multiple places, given this modifier is scarcely used it doesn't seem
/// worth the per-call gas cost here.
modifier onlyMinter() {
require(msg.sender == seriesMinter, "Only callable by minter");
_;
}
/// @notice Open a new Series of Cheeze Wizards! Can only be called by the COO when no Series is open.
/// @param minter The address which is allowed to mint Wizards in this series. This contract does not
/// assume that the minter is a smart contract, but it will presumably be in the vast majority
/// of the cases. A minter has absolute control over the creation of new Wizards in an open
/// Series, but CAN NOT manipulate a Series after it has been close, and CAN NOT mainpulate
/// any Wizards that don't belong to its own Series. (Even if the same minting address is used
/// for multiple Series, the Minter only has power over the currently open Series.)
/// @param reservedIds The number of IDs (from 1 to reservedIds, inclusive) that are reserved for minting
/// reserved Wizards. (We use the term "reserved" here, instead of Exclusive, because there
/// are times -- such as during the importation of the PreSale -- when we need to reserve a
/// block of IDs for Wizards that aren't what a user would think of as "exclusive". In Series
/// 0, the reserved IDs will include all Exclusive Wizards and Presale Wizards. In other Series
/// it might also be the case that the set of "reserved IDs" doesn't exactly match the set of
/// "exclusive" IDs.)
function openSeries(address minter, uint256 reservedIds) external onlyCOO returns (uint64 seriesId) {
require(seriesMinter == address(0), "A series is already open");
require(minter != address(0), "Minter address cannot be 0");
// NOTE: The seriesIndex is updated when the Series is _closed_, not when it's opened.
// (The first Series is Series #0.) So in this function, we just leave the seriesIndex alone.
seriesMinter = minter;
nextWizardIndex = reservedIds + 1;
emit SeriesOpen(seriesIndex, reservedIds);
return seriesIndex;
}
/// @notice Closes the current Wizard Series. Once a Series has been closed, it is forever sealed and
/// no more Wizards in that Series can ever be minted! Can only be called by the COO when a Series
/// is open.
///
/// NOTE: A series can be closed by the COO or the Minter. (It's assumed that some minters will
/// know when they are done, and others will need to be shut off manually by the COO.)
function closeSeries() external duringSeries {
require(
msg.sender == seriesMinter || msg.sender == cooAddress,
"Only Minter or COO can close a Series");
seriesMinter = address(0);
emit SeriesClose(seriesIndex);
// Set up the next series.
seriesIndex += 1;
nextWizardIndex = 0;
}
/// @notice ERC-165 Query Function.
function supportsInterface(bytes4 interfaceId) public view returns (bool) {
return interfaceId == _INTERFACE_ID_WIZARDGUILD || super.supportsInterface(interfaceId);
}
/// @notice Returns the information associated with the given Wizard
/// owner - The address that owns this Wizard
/// innatePower - The innate power level of this Wizard, set when minted and entirely
/// immutable
/// affinity - The Elemental Affinity of this Wizard. For most Wizards, this is set
/// when they are minted, but some exclusive Wizards are minted with an affinity
/// of 0 (ELEMENT_NOTSET). A Wizard with an NOTSET affinity should NOT be able
/// to participate in Tournaments. Once the affinity of a Wizard is set to a non-zero
/// value, it can never be changed again.
/// metadata - A 256-bit hash of the Wizard's metadata, which is stored off chain. This
/// contract doesn't specify format of this hash, nor the off-chain storage mechanism
/// but, let's be honest, it's probably an IPFS SHA-256 hash.
///
/// NOTE: Series zero Wizards have one of four Affinities: Neutral (1), Fire (2), Water (3)
/// or Air (4, sometimes called "Wind" in the code). Future Wizard Series may have
/// additional Affinities, and clients of this API should be prepared for that
/// eventuality.
function getWizard(uint256 id) public view returns (address owner, uint88 innatePower, uint8 affinity, bytes32 metadata) {
Wizard memory wizard = wizardsById[id];
require(wizard.owner != address(0), "Wizard does not exist");
(owner, innatePower, affinity, metadata) = (wizard.owner, wizard.innatePower, wizard.affinity, wizard.metadata);
}
/// @notice A function to be called that conjures a whole bunch of Wizards at once! You know how
/// there's "a pride of lions", "a murder of crows", and "a parliament of owls"? Well, with this
/// here function you can conjure yourself "a stench of Cheeze Wizards"!
///
/// Unsurprisingly, this method can only be called by the registered minter for a Series.
/// @dev This function DOES NOT CALL onERC721Received() as required by the ERC-721 standard. It is
/// REQUIRED that the Minter calls onERC721Received() after calling this function. The following
/// code snippet should suffice:
/// // Ensure the Wizard is being assigned to an ERC-721 aware address (either an external address,
/// // or a smart contract that implements onERC721Received()). We must call onERC721Recieved for
/// // each token created because it's allowed for an ERC-721 receiving contract to reject the
/// // transfer based on the properties of the token.
/// if (isContract(owner)) {
/// for (uint256 i = 0; i < wizardIds.length; i++) {
/// bytes4 retval = IERC721Receiver(owner).onERC721Received(owner, address(0), wizardIds[i], "");
/// require(retval == _ERC721_RECEIVED, "Contract owner didn't accept ERC721 transfer");
/// }
/// }
/// Although it would be convenient for mintWizards to call onERC721Recieved, it opens us up to potential
/// reentrancy attacks if the Minter needs to do more state updates after mintWizards() returns.
/// @param powers the power level of each wizard
/// @param affinities the Elements of the wizards to create
/// @param owner the address that will own the newly created Wizards
function mintWizards(
uint88[] calldata powers,
uint8[] calldata affinities,
address owner
) external onlyMinter returns (uint256[] memory wizardIds)
{
require(affinities.length == powers.length, "Inconsistent parameter lengths");
// allocate result array
wizardIds = new uint256[](affinities.length);
// We take this storage variables, and turn it into a local variable for the course
// of this loop to save about 5k gas per wizard.
uint256 tempWizardId = (uint256(seriesIndex) << seriesOffset) + nextWizardIndex;
for (uint256 i = 0; i < affinities.length; i++) {
wizardIds[i] = tempWizardId;
tempWizardId++;
_createWizard(wizardIds[i], owner, powers[i], affinities[i]);
}
nextWizardIndex = tempWizardId & indexMask;
}
/// @notice A function to be called that mints a Series of Wizards in the reserved ID range, can only
/// be called by the Minter for this Series.
/// @dev This function DOES NOT CALL onERC721Received() as required by the ERC-721 standard. It is
/// REQUIRED that the Minter calls onERC721Received() after calling this function. See the note
/// above on mintWizards() for more info.
/// @param wizardIds the ID values to use for each Wizard, must be in the reserved range of the current Series.
/// @param powers the power level of each Wizard.
/// @param affinities the Elements of the Wizards to create.
/// @param owner the address that will own the newly created Wizards.
function mintReservedWizards(
uint256[] calldata wizardIds,
uint88[] calldata powers,
uint8[] calldata affinities,
address owner
)
external onlyMinter
{
require(
wizardIds.length == affinities.length &&
wizardIds.length == powers.length, "Inconsistent parameter lengths");
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 currentId = wizardIds[i];
require((currentId & seriesMask) == (uint256(seriesIndex) << seriesOffset), "Wizards not in current series");
// Ideally, we would compare the requested Wizard index against the reserved range directly. However,
// it's a bit wasteful to spend storage on a reserved range variable when we can combine some known
// true facts instead:
// - nextWizardIndex is initialized to reservedRange + 1 when the Series was opend
// - nextWizardIndex is only incremented when a new Wizard is created
// - therefore, the only empty Wizard IDs less than nextWizardIndex are in the reserved range.
// - _conjureWizard() will abort if we try to reuse an ID.
// Combining all of the above, we know that, if the requested index is less than the next index, it
// either points to a reserved slot or an occupied slot. Trying to reuse an occupied slot will fail,
// so just checking against nextWizardIndex is sufficient to ensure we're pointing at a reserved slot.
require((currentId & indexMask) < nextWizardIndex, "Wizards not in reserved range");
_createWizard(currentId, owner, powers[i], affinities[i]);
}
}
/// @notice Sets the metadata values for a list of Wizards. The metadata for a Wizard can only be set once,
/// can only be set by the COO or Minter, and can only be set while the Series is still open. Once
/// a Series is closed, the metadata is locked forever!
/// @param wizardIds the ID values of the Wizards to apply metadata changes to.
/// @param metadata the raw metadata values for each Wizard. This contract does not define how metadata
/// should be interpreted, but it is likely to be a 256-bit hash of a complete metadata package
/// accessible via IPFS or similar.
function setMetadata(uint256[] calldata wizardIds, bytes32[] calldata metadata) external duringSeries {
require(msg.sender == seriesMinter || msg.sender == cooAddress, "Only Minter or COO can set metadata");
require(wizardIds.length == metadata.length, "Inconsistent parameter lengths");
for (uint256 i = 0; i < wizardIds.length; i++) {
uint256 currentId = wizardIds[i];
bytes32 currentMetadata = metadata[i];
require((currentId & seriesMask) == (uint256(seriesIndex) << seriesOffset), "Wizards not in current series");
require(wizardsById[currentId].metadata == bytes32(0), "Metadata already set");
require(currentMetadata != bytes32(0), "Invalid metadata");
wizardsById[currentId].metadata = currentMetadata;
emit MetadataSet(currentId, currentMetadata);
}
}
/// @notice Sets the affinity for a Wizard that doesn't already have its elemental affinity chosen.
/// Only usable for Exclusive Wizards (all non-Exclusives must have their affinity chosen when
/// conjured.) Even Exclusives can't change their affinity once it's been chosen.
///
/// NOTE: This function can only be called by the Series minter, and (therefore) only while the
/// Series is open. A Wizard that has no affinity when a Series is closed will NEVER have an Affinity.
/// @param wizardId The ID of the Wizard to update affinity of.
/// @param newAffinity The new affinity of the Wizard.
function setAffinity(uint256 wizardId, uint8 newAffinity) external onlyMinter {
require((wizardId & seriesMask) == (uint256(seriesIndex) << seriesOffset), "Wizard not in current series");
Wizard storage wizard = wizardsById[wizardId];
require(wizard.affinity == ELEMENT_NOTSET, "Affinity can only be chosen once");
// set the affinity
wizard.affinity = newAffinity;
// Tell the world this wizards now has an affinity!
emit WizardAffinityAssigned(wizardId, newAffinity);
}
/// @notice Returns true if the given "spender" address is allowed to manipulate the given token
/// (either because it is the owner of that token, has been given approval to manage that token)
function isApprovedOrOwner(address spender, uint256 tokenId) public view returns (bool) {
return _isApprovedOrOwner(spender, tokenId);
}
/// @notice Verifies that a given signature represents authority to control the given Wizard ID,
/// reverting otherwise. It handles three cases:
/// - The simplest case: The signature was signed with the private key associated with
/// an external address that is the owner of this Wizard.
/// - The signature was generated with the private key associated with an external address
/// that is "approved" for working with this Wizard ID. (See the Wizard Guild and/or
/// the ERC-721 spec for more information on "approval".)
/// - The owner or approval address (as in cases one or two) is a smart contract
/// that conforms to ERC-1654, and accepts the given signature as being valid
/// using its own internal logic.
///
/// NOTE: This function DOES NOT accept a signature created by an address that was given "operator
/// status" (as granted by ERC-721's setApprovalForAll() functionality). Doing so is
/// considered an extreme edge case that can be worked around where necessary.
/// @param wizardId The Wizard ID whose control is in question
/// @param hash The message hash we are authenticating against
/// @param sig the signature data; can be longer than 65 bytes for ERC-1654
function verifySignature(uint256 wizardId, bytes32 hash, bytes memory sig) public view {
// First see if the signature belongs to the owner (the most common case)
address owner = ownerOf(wizardId);
if (_validSignatureForAddress(owner, hash, sig)) {
return;
}
// Next check if the signature belongs to the approved address
address approved = getApproved(wizardId);
if (_validSignatureForAddress(approved, hash, sig)) {
return;
}
revert("Invalid signature");
}
/// @notice Convienence function that verifies signatures for two wizards using equivalent logic to
/// verifySignature(). Included to save on cross-contract calls in the common case where we
/// are verifying the signatures of two Wizards who wish to enter into a Duel.
/// @param wizardId1 The first Wizard ID whose control is in question
/// @param wizardId2 The second Wizard ID whose control is in question
/// @param hash1 The message hash we are authenticating against for the first Wizard
/// @param hash2 The message hash we are authenticating against for the first Wizard
/// @param sig1 the signature data corresponding to the first Wizard; can be longer than 65 bytes for ERC-1654
/// @param sig2 the signature data corresponding to the second Wizard; can be longer than 65 bytes for ERC-1654
function verifySignatures(
uint256 wizardId1,
uint256 wizardId2,
bytes32 hash1,
bytes32 hash2,
bytes calldata sig1,
bytes calldata sig2) external view
{
verifySignature(wizardId1, hash1, sig1);
verifySignature(wizardId2, hash2, sig2);
}
/// @notice An internal function that checks if a given signature is a valid signature for a
/// specific address on a particular hash value. Checks for ERC-1654 compatibilty
/// first (where the possibleSigner is a smart contract that implements its own
/// signature validation), and falls back to ecrecover() otherwise.
function _validSignatureForAddress(address possibleSigner, bytes32 hash, bytes memory signature)
internal view returns(bool)
{
if (possibleSigner == address(0)) {
// The most basic Bozo check: The zero address can never be a valid signer!
return false;
} else if (Address.isContract(possibleSigner)) {
// If the address is a contract, it either implements ERC-1654 (and will validate the signature
// itself), or we have no way of confirming that this signature matches this address. In other words,
// if this address is a contract, there's no point in "falling back" to ecrecover().
if (doesContractImplementInterface(possibleSigner, ERC1654_VALIDSIGNATURE)) {
// cast to ERC1654
ERC1654 tso = ERC1654(possibleSigner);
bytes4 result = tso.isValidSignature(hash, signature);
if (result == ERC1654_VALIDSIGNATURE) {
return true;
}
}
return false;
} else {
// Not a contract, check for a match against an external address
(bytes32 r, bytes32 s, uint8 v) = SigTools._splitSignature(signature);
address signer = ecrecover(hash, v, r, s);
// Note: Signer could be address(0) here, but we already checked that possibleSigner isn't zero
return (signer == possibleSigner);
}
}
}
| @dev The AccessControl constructor sets the `ceoAddress` to the sender account. Also initializes the COO and CFO to the passed values (CFO is optional and can be address(0)). @param newCooAddress The initial COO address to set @param newCfoAddress The initial CFO to set (optional) | constructor(address newCooAddress, address payable newCfoAddress) public {
_setCeo(msg.sender);
setCoo(newCooAddress);
if (newCfoAddress != address(0)) {
setCfo(newCfoAddress);
}
}
| 2,503,821 | [
1,
1986,
24349,
3885,
1678,
326,
1375,
311,
83,
1887,
68,
358,
326,
5793,
2236,
18,
8080,
1377,
11643,
326,
7910,
51,
471,
385,
3313,
358,
326,
2275,
924,
261,
39,
3313,
353,
3129,
471,
848,
506,
1758,
12,
20,
13,
2934,
225,
394,
4249,
83,
1887,
1021,
2172,
7910,
51,
1758,
358,
444,
225,
394,
39,
617,
1887,
1021,
2172,
385,
3313,
358,
444,
261,
10444,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
3885,
12,
2867,
394,
4249,
83,
1887,
16,
1758,
8843,
429,
394,
39,
617,
1887,
13,
1071,
288,
203,
3639,
389,
542,
39,
4361,
12,
3576,
18,
15330,
1769,
203,
3639,
444,
4249,
83,
12,
2704,
4249,
83,
1887,
1769,
203,
203,
3639,
309,
261,
2704,
39,
617,
1887,
480,
1758,
12,
20,
3719,
288,
203,
5411,
11440,
617,
12,
2704,
39,
617,
1887,
1769,
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
]
|
./full_match/1/0xDb149235B6F40dC08810AA69869783Be101790e7/sources/contracts/0.8.9/DepositSecurityModule.sol | * Returns whether deposits were paused./ | function isPaused() external view returns (bool) {
return paused;
}
| 3,870,628 | [
1,
1356,
2856,
443,
917,
1282,
4591,
17781,
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,
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,
445,
353,
28590,
1435,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
17781,
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,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0xd95212B72E3919d3A48e1Ca44E4233d12591BBE6/sources/localhost/antimatter/BridgeFactory.sol | config[_feeCreate_] = 0.200 ether; | function __MappingTokenFactory_init_unchained(string memory _name,address _implTokenMapped, address _implMappableToken, address _implMappingToken, address _feeTo) public governance {
config[_fee_] = 0.005 ether;
config[_feeTo_] = uint(_feeTo);
config[_minSignatures_] = 1;
config[_uniswapRounter_] = uint(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
name = _name;
DOMAIN_SEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _chainId(), address(this)));
upgradeProductImplementationsTo_(_implTokenMapped, _implMappableToken, _implMappingToken);
}
| 686,033 | [
1,
1425,
63,
67,
21386,
1684,
67,
65,
5397,
273,
374,
18,
6976,
225,
2437,
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
]
| [
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,
1001,
3233,
1345,
1733,
67,
2738,
67,
4384,
8707,
12,
1080,
3778,
389,
529,
16,
2867,
389,
11299,
1345,
12868,
16,
1758,
389,
11299,
863,
19586,
1345,
16,
1758,
389,
11299,
3233,
1345,
16,
1758,
389,
21386,
774,
13,
1071,
314,
1643,
82,
1359,
288,
203,
3639,
642,
63,
67,
21386,
67,
65,
21821,
273,
374,
18,
28564,
225,
2437,
31,
203,
3639,
642,
63,
67,
21386,
774,
67,
65,
7682,
273,
2254,
24899,
21386,
774,
1769,
203,
3639,
642,
63,
67,
1154,
23918,
67,
65,
1171,
273,
404,
31,
203,
3639,
642,
63,
67,
318,
291,
91,
438,
54,
2096,
67,
65,
7734,
273,
2254,
12,
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,
1769,
203,
3639,
508,
273,
389,
529,
31,
203,
203,
3639,
27025,
67,
4550,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
12,
18192,
67,
2399,
15920,
16,
417,
24410,
581,
5034,
12,
3890,
12,
529,
13,
3631,
389,
5639,
548,
9334,
1758,
12,
2211,
3719,
1769,
203,
3639,
8400,
4133,
5726,
1012,
774,
67,
24899,
11299,
1345,
12868,
16,
389,
11299,
863,
19586,
1345,
16,
389,
11299,
3233,
1345,
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
]
|
// Goals
// - Defensibility -> Kick out malicious members via forceRagequit
// - Separation of Wealth and Power -> voting / loot tokens - grant pool can't be claimed (controlled by separate contract?)
// - batch proposals -> 1 month between proposal batches, 2 week voting period, 2 week grace period
// - better spam protection -> exponential increase in deposit for same member / option to claim deposit
// - replacing members?
// - hasn't been discussed
// - accountability to stakeholders
// - some kind of siganlling
pragma solidity 0.5.3;
import "./oz/SafeMath.sol";
import "./oz/IERC20.sol";
import "./GuildBank.sol";
contract Moloch {
using SafeMath for uint256;
/***************
GLOBAL CONSTANTS
***************/
uint256 public periodDuration; // default = 17280 = 4.8 hours in seconds (5 periods per day)
uint256 public votingPeriodLength; // default = 35 periods (7 days)
uint256 public gracePeriodLength; // default = 35 periods (7 days)
uint256 public abortWindow; // default = 5 periods (1 day)
uint256 public proposalDeposit; // default = 10 ETH (~$1,000 worth of ETH at contract deployment)
uint256 public dilutionBound; // default = 3 - maximum multiplier a YES voter will be obligated to pay in case of mass ragequit
uint256 public processingReward; // default = 0.1 - amount of ETH to give to whoever processes a proposal
uint256 public summoningTime; // needed to determine the current period
bool public quadraticMode; // if it will computed quadratic votes over traditional ones.
IERC20 public approvedToken; // approved token contract reference; default = wETH
GuildBank public guildBank; // guild bank contract reference
// HARD-CODED LIMITS
// These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations
// with periods or shares, yet big enough to not limit reasonable use cases.
uint256 constant MAX_VOTING_PERIOD_LENGTH = 10**18; // maximum length of voting period
uint256 constant MAX_GRACE_PERIOD_LENGTH = 10**18; // maximum length of grace period
uint256 constant MAX_DILUTION_BOUND = 10**18; // maximum dilution bound
uint256 constant MAX_NUMBER_OF_SHARES = 10**18; // maximum number of shares that can be minted
/***************
EVENTS
***************/
event SubmitProposal(uint256 proposalIndex, address indexed delegateKey, address indexed memberAddress, address[] indexed candidates, uint256 tokenTribute, uint256 sharesRequested);
event SubmitVote(uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, address indexed candidate, uint256 votes, uint256 quadraticVotes);
event ProcessProposal(uint256 indexed proposalIndex, address indexed electedCandidate, address indexed memberAddress, uint256 tokenTribute, uint256 sharesRequested, bool didPass);
event Ragequit(address indexed memberAddress, uint256 sharesToBurn);
event Abort(uint256 indexed proposalIndex, address applicantAddress);
event UpdateDelegateKey(address indexed memberAddress, address newDelegateKey);
event SummonComplete(address indexed summoner, uint256 shares);
/******************
INTERNAL ACCOUNTING
******************/
uint256 public totalShares = 0; // total shares across all members
uint256 public totalSharesRequested = 0; // total shares that have been requested in unprocessed proposals
struct Ballot {
uint256[] votes,
uint256[] quadraticVotes,
address[] candidate
}
struct Member {
address delegateKey; // the key responsible for submitting proposals and voting - defaults to member address unless updated
uint256 shares; // the # of shares assigned to this member
bool exists; // always true once a member has been created
uint256 highestIndexVote; // highest proposal index # on which the member voted YES
}
struct Proposal {
address proposer; // the member who submitted the proposal
address[] candidates; // list of candidates to include in a ballot
uint256[] totalVotes; // total votes each candidate received
uint256[] totalQuadraticVotes; // calculation of quadratic votes for each candidate
uint256 sharesRequested; // the # of shares the applicant is requesting
uint256 startingPeriod; // the period in which voting can start for this proposal
uint256 yesVotes; // the total number of YES votes for this proposal
uint256 noVotes; // the total number of NO votes for this proposal
bool processed; // true only if the proposal has been processed
bool didPass; // true only if the proposal has elected a candidate
address electedCandidate; // address of an electeed candidate
bool aborted; // true only if applicant calls "abort" fn before end of voting period
uint256 tokenTribute; // amount of tokens offered as tribute
string details; // proposal details - could be IPFS hash, plaintext, or JSON
uint256 maxTotalSharesAtYesVote; // the maximum # of total shares encountered at a yes vote on this proposal
mapping (address => Ballot) votesByMember; // list of candidates and corresponding votes
}
mapping (address => Member) public members;
mapping (address => address) public memberAddressByDelegateKey;
Proposal[] public proposalQueue;
/********
MODIFIERS
********/
modifier onlyMember {
require(members[msg.sender].shares > 0, "Moloch::onlyMember - not a member");
_;
}
modifier onlyDelegate {
require(members[memberAddressByDelegateKey[msg.sender]].shares > 0, "Moloch::onlyDelegate - not a delegate");
_;
}
/********
FUNCTIONS
********/
constructor(
address summoner,
address _approvedToken,
uint256 _periodDuration,
uint256 _votingPeriodLength,
uint256 _gracePeriodLength,
uint256 _abortWindow,
uint256 _proposalDeposit,
uint256 _dilutionBound,
uint256 _processingReward,
uint256 _quadraticMode
) public {
require(summoner != address(0), "Moloch::constructor - summoner cannot be 0");
require(_approvedToken != address(0), "Moloch::constructor - _approvedToken cannot be 0");
require(_periodDuration > 0, "Moloch::constructor - _periodDuration cannot be 0");
require(_votingPeriodLength > 0, "Moloch::constructor - _votingPeriodLength cannot be 0");
require(_votingPeriodLength <= MAX_VOTING_PERIOD_LENGTH, "Moloch::constructor - _votingPeriodLength exceeds limit");
require(_gracePeriodLength <= MAX_GRACE_PERIOD_LENGTH, "Moloch::constructor - _gracePeriodLength exceeds limit");
require(_abortWindow > 0, "Moloch::constructor - _abortWindow cannot be 0");
require(_abortWindow <= _votingPeriodLength, "Moloch::constructor - _abortWindow must be smaller than or equal to _votingPeriodLength");
require(_dilutionBound > 0, "Moloch::constructor - _dilutionBound cannot be 0");
require(_dilutionBound <= MAX_DILUTION_BOUND, "Moloch::constructor - _dilutionBound exceeds limit");
require(_proposalDeposit >= _processingReward, "Moloch::constructor - _proposalDeposit cannot be smaller than _processingReward");
approvedToken = IERC20(_approvedToken);
guildBank = new GuildBank(_approvedToken);
periodDuration = _periodDuration;
votingPeriodLength = _votingPeriodLength;
gracePeriodLength = _gracePeriodLength;
abortWindow = _abortWindow;
proposalDeposit = _proposalDeposit;
dilutionBound = _dilutionBound;
processingReward = _processingReward;
quadraticMode = _quadraticMode;
summoningTime = now;
members[summoner] = Member(summoner, 1, true, 0);
memberAddressByDelegateKey[summoner] = summoner;
totalShares = 1;
emit SummonComplete(summoner, 1);
}
/*****************
PROPOSAL FUNCTIONS
*****************/
function submitProposal(
address[] candidates,
uint256 tokenTribute,
uint256 sharesRequested,
string memory details
)
public
onlyDelegate
{
require(candidates.length > 0, "QuadraticMoloch::submitProposal - at least 1 candidate is required.");
for (uint i=0; i < candidates.length; i++) {
require(candidates[i] != address(0), "Moloch::submitProposal - candidate cannot be 0");
}
// Make sure we won't run into overflows when doing calculations with shares.
// Note that totalShares + totalSharesRequested + sharesRequested is an upper bound
// on the number of shares that can exist until this proposal has been processed.
require(totalShares.add(totalSharesRequested).add(sharesRequested) <= MAX_NUMBER_OF_SHARES, "Moloch::submitProposal - too many shares requested");
totalSharesRequested = totalSharesRequested.add(sharesRequested);
address memberAddress = memberAddressByDelegateKey[msg.sender];
// collect proposal deposit from proposer and store it in the Moloch until the proposal is processed
require(approvedToken.transferFrom(msg.sender, address(this), proposalDeposit), "Moloch::submitProposal - proposal deposit token transfer failed");
// collect tribute from candidate list and store it in the Moloch until the proposal is processed
for (uint k=0; k < candidates.length; k++) {
require(approvedToken.transferFrom(candidates[k], address(this), tokenTribute), "Moloch::submitProposal - tribute token transfer failed");
}
// compute startingPeriod for proposal
uint256 startingPeriod = max(
getCurrentPeriod(),
proposalQueue.length == 0 ? 0 : proposalQueue[proposalQueue.length.sub(1)].startingPeriod
).add(1);
// create proposal ...
Proposal memory proposal = Proposal({
proposer: memberAddress,
candidates: candidates,
sharesRequested: sharesRequested,
startingPeriod: startingPeriod,
electedCandidate: address(0x0),
processed: false,
aborted: false,
tokenTribute: tokenTribute,
details: details,
maxTotalSharesAtYesVote: 0
});
// ... and append it to the queue
proposalQueue.push(proposal);
uint256 proposalIndex = proposalQueue.length.sub(1);
emit SubmitProposal(proposalIndex, msg.sender, memberAddress, candidates, tokenTribute, sharesRequested);
}
function submitVote(uint256 proposalIndex, address candidate, uint256 votes) public onlyDelegate {
address memberAddress = memberAddressByDelegateKey[msg.sender];
Member storage member = members[memberAddress];
require(proposalIndex < proposalQueue.length, "Moloch::submitVote - proposal does not exist");
Proposal storage proposal = proposalQueue[proposalIndex];
require(votes > 0, "QuadraticMoloch::submitVote - at least one vote must be cast");
require(getCurrentPeriod() >= proposal.startingPeriod, "Moloch::submitVote - voting period has not started");
require(!hasVotingPeriodExpired(proposal.startingPeriod), "Moloch::submitVote - proposal voting period has expired");
require(!proposal.aborted, "Moloch::submitVote - proposal has been aborted");
// store vote
Ballot memberBallot = proposal.votesByMember[memberAddress];
uint256 totalVotes = 0;
uint256 newVotes = 0;
bool update = false;
uint256 quadraticVotes = 0;
for (uint i = 0; i < memberBallot.candidate.length; i++) {
if (memberBallot.candidate[i] == candidate) {
update = true;
newVotes = memberBallot.votes[i].add(votes);
quadraticVotes = sqrt(newVotes);
memberBallot.votes[i] = newVotes;
memberBallot.quadraticVotes[i] = quadraticVotes;
}
totalVotes = totalVotes.add(memberBallot.votes[i]);
}
require(totalVotes <= member.shares, "QuadraticMoloch::submitVote - not enough shares to cast this quantity of votes");
if (!update) {
memberBallot.candidate.push(candidate);
memberBallot.votes.push(votes);
quadraticVotes = sqrt(votes);
memberBallot.quadraticVotes.push(quadraticVotes);
proposal.votesByMember[memberAddress] = memberBallot;
}
// count vote
update = false;
for (uint k = 0; k < proposal.candidates.length; k++) {
if (proposal.candidates[k] == candidate) {
proposal.totalVotes[k] = proposal.totalVotes[k].add(votes);
proposal.totalQuadraticVotes[k] = sqrt(proposal.totalVotes[k]);
update = true;
}
}
if (!update) {
proposal.candidates.push(candidate);
proposal.totalVotes.push(votes);
proposal.totalQuadraticVotes.push(sqrt(votes));
}
if (proposalIndex > member.highestIndexVote) {
member.highestIndexVote = proposalIndex;
}
emit SubmitVote(proposalIndex, msg.sender, memberAddress, candidate, votes, quadraticVotes);
}
function processProposal(uint256 proposalIndex) public {
require(proposalIndex < proposalQueue.length, "Moloch::processProposal - proposal does not exist");
Proposal storage proposal = proposalQueue[proposalIndex];
require(getCurrentPeriod() >= proposal.startingPeriod.add(votingPeriodLength).add(gracePeriodLength), "Moloch::processProposal - proposal is not ready to be processed");
require(proposal.processed == false, "Moloch::processProposal - proposal has already been processed");
require(proposalIndex == 0 || proposalQueue[proposalIndex.sub(1)].processed, "Moloch::processProposal - previous proposal must be processed");
proposal.processed = true;
totalSharesRequested = totalSharesRequested.sub(proposal.sharesRequested);
// Get elected candidate
uint256 largest = 0;
uint elected = 0;
require(proposal.totalVotes.length > 0, "QuadraticMoloch::processProposal - this proposal has not received any votes.");
bool didPass = true;
for (uint i = 0; i < proposal.totalVotes.length; i++) {
if (quadraticMode) {
if (proposal.totalQuadraticVotes[i] > largest) {
largest = proposal.totalQuadraticVotes[i];
elected = i;
}
} else if (proposal.totalVotes[i] > largest) {
largest = proposal.totalVotes[i];
elected = i;
}
}
electedCandidate = proposal.candidates[i];
// Make the proposal fail if the dilutionBound is exceeded
if (totalShares.mul(dilutionBound) < proposal.maxTotalSharesAtYesVote) {
didPass = false;
}
// PROPOSAL PASSED
if (didPass && !proposal.aborted) {
proposal.didPass = true;
// if the elected candidate is already a member, add to their existing shares
if (members[electedCandidate].exists) {
members[electedCandidate].shares = members[electedCandidate].shares.add(proposal.sharesRequested);
// the applicant is a new member, create a new record for them
} else {
// if the applicant address is already taken by a member's delegateKey, reset it to their member address
if (members[memberAddressByDelegateKey[electedCandidate]].exists) {
address memberToOverride = memberAddressByDelegateKey[electedCandidate];
memberAddressByDelegateKey[memberToOverride] = memberToOverride;
members[memberToOverride].delegateKey = memberToOverride;
}
// use elected candidate address as delegateKey by default
members[electedCandidate] = Member(electedCandidate, proposal.sharesRequested, true, 0);
memberAddressByDelegateKey[electedCandidate] = electedCandidate;
}
// mint new shares
totalShares = totalShares.add(proposal.sharesRequested);
// transfer tokens to guild bank
require(
approvedToken.transfer(address(guildBank), proposal.tokenTribute),
"Moloch::processProposal - token transfer to guild bank failed"
);
// PROPOSAL FAILED OR ABORTED
} else {
// return all tokens to the applicant
require(
approvedToken.transfer(electedCandidate, proposal.tokenTribute),
"Moloch::processProposal - failing vote token transfer failed"
);
}
// send msg.sender the processingReward
require(
approvedToken.transfer(msg.sender, processingReward),
"Moloch::processProposal - failed to send processing reward to msg.sender"
);
// return deposit to proposer (subtract processing reward)
require(
approvedToken.transfer(proposal.proposer, proposalDeposit.sub(processingReward)),
"Moloch::processProposal - failed to return proposal deposit to proposer"
);
emit ProcessProposal(
proposalIndex,
electedCandidate,
proposal.proposer,
proposal.tokenTribute,
proposal.sharesRequested,
didPass
);
}
function ragequit(uint256 sharesToBurn) public onlyMember {
uint256 initialTotalShares = totalShares;
Member storage member = members[msg.sender];
require(member.shares >= sharesToBurn, "Moloch::ragequit - insufficient shares");
require(canRagequit(member.highestIndexVote), "Moloch::ragequit - cant ragequit until highest index proposal member voted YES on is processed");
// burn shares
member.shares = member.shares.sub(sharesToBurn);
totalShares = totalShares.sub(sharesToBurn);
// instruct guildBank to transfer fair share of tokens to the ragequitter
require(
guildBank.withdraw(msg.sender, sharesToBurn, initialTotalShares),
"Moloch::ragequit - withdrawal of tokens from guildBank failed"
);
emit Ragequit(msg.sender, sharesToBurn);
}
function abort(uint256 proposalIndex) public {
require(proposalIndex < proposalQueue.length, "Moloch::abort - proposal does not exist");
Proposal storage proposal = proposalQueue[proposalIndex];
require(msg.sender == proposal.applicant, "Moloch::abort - msg.sender must be applicant");
require(getCurrentPeriod() < proposal.startingPeriod.add(abortWindow), "Moloch::abort - abort window must not have passed");
require(!proposal.aborted, "Moloch::abort - proposal must not have already been aborted");
uint256 tokensToAbort = proposal.tokenTribute;
proposal.tokenTribute = 0;
proposal.aborted = true;
// return all tokens to the applicant
require(
approvedToken.transfer(proposal.applicant, tokensToAbort),
"Moloch::processProposal - failed to return tribute to applicant"
);
emit Abort(proposalIndex, msg.sender);
}
function updateDelegateKey(address newDelegateKey) public onlyMember {
require(newDelegateKey != address(0), "Moloch::updateDelegateKey - newDelegateKey cannot be 0");
// skip checks if member is setting the delegate key to their member address
if (newDelegateKey != msg.sender) {
require(!members[newDelegateKey].exists, "Moloch::updateDelegateKey - cant overwrite existing members");
require(!members[memberAddressByDelegateKey[newDelegateKey]].exists, "Moloch::updateDelegateKey - cant overwrite existing delegate keys");
}
Member storage member = members[msg.sender];
memberAddressByDelegateKey[member.delegateKey] = address(0);
memberAddressByDelegateKey[newDelegateKey] = msg.sender;
member.delegateKey = newDelegateKey;
emit UpdateDelegateKey(msg.sender, newDelegateKey);
}
/***************
GETTER FUNCTIONS
***************/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x >= y ? x : y;
}
function sqrt(uint256 x) internal pure returns (uint256 y) {
uint256 z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
function getCurrentPeriod() public view returns (uint256) {
return now.sub(summoningTime).div(periodDuration);
}
function getProposalQueueLength() public view returns (uint256) {
return proposalQueue.length;
}
// can only ragequit if the latest proposal you voted YES on has been processed
function canRagequit(uint256 highestIndexVote) public view returns (bool) {
require(highestIndexVote < proposalQueue.length, "Moloch::canRagequit - proposal does not exist");
return proposalQueue[highestIndexVote].processed;
}
function hasVotingPeriodExpired(uint256 startingPeriod) public view returns (bool) {
return getCurrentPeriod() >= startingPeriod.add(votingPeriodLength);
}
function getMemberProposalVote(address memberAddress, uint256 proposalIndex) public view returns (Vote) {
require(members[memberAddress].exists, "Moloch::getMemberProposalVote - member doesn't exist");
require(proposalIndex < proposalQueue.length, "Moloch::getMemberProposalVote - proposal doesn't exist");
return proposalQueue[proposalIndex].votesByMember[memberAddress];
}
}
| collect tribute from candidate list and store it in the Moloch until the proposal is processed create proposal ... | function submitProposal(
address[] candidates,
uint256 tokenTribute,
uint256 sharesRequested,
string memory details
)
public
onlyDelegate
{
require(candidates.length > 0, "QuadraticMoloch::submitProposal - at least 1 candidate is required.");
for (uint i=0; i < candidates.length; i++) {
require(candidates[i] != address(0), "Moloch::submitProposal - candidate cannot be 0");
}
totalSharesRequested = totalSharesRequested.add(sharesRequested);
address memberAddress = memberAddressByDelegateKey[msg.sender];
for (uint k=0; k < candidates.length; k++) {
require(approvedToken.transferFrom(candidates[k], address(this), tokenTribute), "Moloch::submitProposal - tribute token transfer failed");
}
getCurrentPeriod(),
proposalQueue.length == 0 ? 0 : proposalQueue[proposalQueue.length.sub(1)].startingPeriod
).add(1);
Proposal memory proposal = Proposal({
proposer: memberAddress,
candidates: candidates,
sharesRequested: sharesRequested,
startingPeriod: startingPeriod,
electedCandidate: address(0x0),
processed: false,
aborted: false,
tokenTribute: tokenTribute,
details: details,
maxTotalSharesAtYesVote: 0
});
uint256 proposalIndex = proposalQueue.length.sub(1);
emit SubmitProposal(proposalIndex, msg.sender, memberAddress, candidates, tokenTribute, sharesRequested);
}
| 12,605,108 | [
1,
14676,
433,
495,
624,
628,
5500,
666,
471,
1707,
518,
316,
326,
490,
355,
9842,
3180,
326,
14708,
353,
5204,
752,
14708,
1372,
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,
4879,
14592,
12,
203,
3639,
1758,
8526,
7965,
16,
203,
3639,
2254,
5034,
1147,
1070,
495,
624,
16,
203,
3639,
2254,
5034,
24123,
11244,
16,
203,
3639,
533,
3778,
3189,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1338,
9586,
203,
565,
288,
203,
3639,
2583,
12,
21635,
18,
2469,
405,
374,
16,
315,
24483,
20004,
49,
355,
9842,
2866,
9297,
14592,
300,
622,
4520,
404,
5500,
353,
1931,
1199,
1769,
203,
3639,
364,
261,
11890,
277,
33,
20,
31,
277,
411,
7965,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2583,
12,
21635,
63,
77,
65,
480,
1758,
12,
20,
3631,
315,
49,
355,
9842,
2866,
9297,
14592,
300,
5500,
2780,
506,
374,
8863,
203,
3639,
289,
203,
203,
203,
3639,
2078,
24051,
11244,
273,
2078,
24051,
11244,
18,
1289,
12,
30720,
11244,
1769,
203,
203,
3639,
1758,
3140,
1887,
273,
3140,
1887,
858,
9586,
653,
63,
3576,
18,
15330,
15533,
203,
203,
203,
3639,
364,
261,
11890,
417,
33,
20,
31,
417,
411,
7965,
18,
2469,
31,
417,
27245,
288,
203,
5411,
2583,
12,
25990,
1345,
18,
13866,
1265,
12,
21635,
63,
79,
6487,
1758,
12,
2211,
3631,
1147,
1070,
495,
624,
3631,
315,
49,
355,
9842,
2866,
9297,
14592,
300,
433,
495,
624,
1147,
7412,
2535,
8863,
203,
3639,
289,
203,
203,
5411,
5175,
5027,
9334,
203,
5411,
14708,
3183,
18,
2469,
422,
374,
692,
374,
294,
14708,
3183,
63,
685,
8016,
3183,
18,
2469,
18,
1717,
12,
21,
13,
8009,
18526,
5027,
203,
3639,
262,
18,
1289,
12,
2
]
|
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/*
▒███████▒ ▒█████ ███▄ ▄███▓ ▄▄▄▄ ██▓▓█████▄▄▄█████▓ ▄▄▄ ▓█████▄ ██▓███ ▒█████ ██▓ ▓█████ ▒███████▒
▒ ▒ ▒ ▄▀░▒██▒ ██▒▓██▒▀█▀ ██▒▓█████▄ ▓██▒▓█ ▀▓ ██▒ ▓▒▒████▄ ▒██▀ ██▌▓██░ ██▒▒██▒ ██▒▓██▒ ▓█ ▀ ▒ ▒ ▒ ▄▀░
░ ▒ ▄▀▒░ ▒██░ ██▒▓██ ▓██░▒██▒ ▄██▒██▒▒███ ▒ ▓██░ ▒░▒██ ▀█▄ ░██ █▌▓██░ ██▓▒▒██░ ██▒▒██░ ▒███ ░ ▒ ▄▀▒░
▄▀▒ ░▒██ ██░▒██ ▒██ ▒██░█▀ ░██░▒▓█ ▄░ ▓██▓ ░ ░██▄▄▄▄██ ░▓█▄ ▌▒██▄█▓▒ ▒▒██ ██░▒██░ ▒▓█ ▄ ▄▀▒ ░
▒███████▒░ ████▓▒░▒██▒ ░██▒░▓█ ▀█▓░██░░▒████▒ ▒██▒ ░ ▓█ ▓██▒░▒████▓ ▒██▒ ░ ░░ ████▓▒░░██████▒░▒████▒▒███████▒
░▒▒ ▓░▒░▒░ ▒░▒░▒░ ░ ▒░ ░ ░░▒▓███▀▒░▓ ░░ ▒░ ░ ▒ ░░ ▒▒ ▓▒█░ ▒▒▓ ▒ ▒▓▒░ ░ ░░ ▒░▒░▒░ ░ ▒░▓ ░░░ ▒░ ░░▒▒ ▓░▒░▒
░░▒ ▒ ░ ▒ ░ ▒ ▒░ ░ ░ ░▒░▒ ░ ▒ ░ ░ ░ ░ ░ ▒ ▒▒ ░ ░ ▒ ▒ ░▒ ░ ░ ▒ ▒░ ░ ░ ▒ ░ ░ ░ ░░░▒ ▒ ░ ▒
░ ░ ░ ░ ░░ ░ ░ ▒ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ▒ ░ ░ ░ ░░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░
░ ░ ░ ░ ░ ░ ░
*/
contract ZombieTadpolez is ERC721URIStorage, Ownable, IERC721Receiver {
using Strings for uint256;
event MintTadpole(address indexed sender, uint256 startWith, uint256 times);
//uints
uint256 public totalTadpolez;
uint256 public constant totalCount = 5555;
uint256 public constant maxBatch = 10;
address public zombieToadzAddress;
address public brainzTokenAddress;
uint32 public breedingCooldown = uint32(8 hours);
uint256[] toadLastBred = new uint256[](5555);
address public contractAddress;
//strings
string public baseURI;
//bool
bool private started;
//constructor args
constructor(string memory name_, string memory symbol_, address _zombieToadzAddress, address _brainzTokenAddress, string memory baseURI_) ERC721(name_, symbol_) {
baseURI = baseURI_;
zombieToadzAddress = _zombieToadzAddress;
brainzTokenAddress = _brainzTokenAddress;
contractAddress = address(this);
}
function totalSupply() public view virtual returns (uint256) {
return totalTadpolez;
}
function _baseURI() internal view virtual override returns (string memory){
return baseURI;
}
function setBaseURI(string memory _newURI) public onlyOwner {
baseURI = _newURI;
}
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(), ".json")) : ".json";
}
function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner {
_setTokenURI(_tokenId, _tokenURI);
}
function setStart(bool _start) public onlyOwner {
started = _start;
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
function currentBrainzCost() public view returns (uint256) {
if (totalTadpolez <= 999) {
return 1000000000000000000000;
}
if (totalTadpolez <= 1999) {
return 2000000000000000000000;
}
if (totalTadpolez <= 2999) {
return 3000000000000000000000;
}
if (totalTadpolez <= 3999) {
return 4000000000000000000000;
}
if (totalTadpolez <= 4999) {
return 5000000000000000000000;
}
if (totalTadpolez <= 5555) {
return 6000000000000000000000;
}
revert();
}
function getToadLastBred(uint256 tokenId) public view returns (uint256) {
return toadLastBred[tokenId];
}
function breedToads(uint256[] calldata _tokenIds, uint256 amount) public {
require(started, "not started");
require(totalTadpolez < totalCount, "too many tadpolez");
require(_tokenIds.length == 2, "you need 2 zombie toads to breed");
require(amount >= currentBrainzCost(), "not enough brainz");
// both toadz given must be owned by the caller of the function
require(IERC721(zombieToadzAddress).ownerOf(_tokenIds[0]) == _msgSender()
&& IERC721(zombieToadzAddress).ownerOf(_tokenIds[1]) == _msgSender(),
"must be the owner of both zombie toadz to breed");
// both toadz must not have been recently bred
require(block.timestamp - toadLastBred[_tokenIds[0]] > breedingCooldown
&& block.timestamp - toadLastBred[_tokenIds[1]] > breedingCooldown,
"one or more zombietoad is on breeding cooldown");
uint256 allowance = IERC20(brainzTokenAddress).allowance(msg.sender, address(this));
require(amount <= allowance,
string(abi.encodePacked("amount greater than allowed value of: ", allowance.toString())));
// Transfer the required amount of brainz to this contract as payment for breeding
IERC20(brainzTokenAddress).transferFrom(msg.sender, address(this), currentBrainzCost());
// Create a tadpole and transfer it to the caller of the function
emit MintTadpole(_msgSender(), totalTadpolez+1, 1);
_mint(_msgSender(), ++totalTadpolez);
// Assign the current time to the toad ids used for this breeding
toadLastBred[_tokenIds[0]] = block.timestamp;
toadLastBred[_tokenIds[1]] = block.timestamp;
}
function withdrawBrainz() public onlyOwner {
uint256 brainzSupply = IERC20(brainzTokenAddress).balanceOf(address(this));
IERC20(brainzTokenAddress).transfer(msg.sender, brainzSupply);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @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];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | uintsstringsboolconstructor args | contract ZombieTadpolez is ERC721URIStorage, Ownable, IERC721Receiver {
using Strings for uint256;
event MintTadpole(address indexed sender, uint256 startWith, uint256 times);
uint256 public totalTadpolez;
uint256 public constant totalCount = 5555;
uint256 public constant maxBatch = 10;
address public zombieToadzAddress;
address public brainzTokenAddress;
uint32 public breedingCooldown = uint32(8 hours);
uint256[] toadLastBred = new uint256[](5555);
address public contractAddress;
string public baseURI;
bool private started;
constructor(string memory name_, string memory symbol_, address _zombieToadzAddress, address _brainzTokenAddress, string memory baseURI_) ERC721(name_, symbol_) {
baseURI = baseURI_;
zombieToadzAddress = _zombieToadzAddress;
brainzTokenAddress = _brainzTokenAddress;
contractAddress = address(this);
}
function totalSupply() public view virtual returns (uint256) {
return totalTadpolez;
}
function _baseURI() internal view virtual override returns (string memory){
return baseURI;
}
function setBaseURI(string memory _newURI) public onlyOwner {
baseURI = _newURI;
}
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(), ".json")) : ".json";
}
function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner {
_setTokenURI(_tokenId, _tokenURI);
}
function setStart(bool _start) public onlyOwner {
started = _start;
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external pure override returns (bytes4) {
return IERC721Receiver.onERC721Received.selector;
}
function currentBrainzCost() public view returns (uint256) {
if (totalTadpolez <= 999) {
return 1000000000000000000000;
}
if (totalTadpolez <= 1999) {
return 2000000000000000000000;
}
if (totalTadpolez <= 2999) {
return 3000000000000000000000;
}
if (totalTadpolez <= 3999) {
return 4000000000000000000000;
}
if (totalTadpolez <= 4999) {
return 5000000000000000000000;
}
if (totalTadpolez <= 5555) {
return 6000000000000000000000;
}
revert();
}
function currentBrainzCost() public view returns (uint256) {
if (totalTadpolez <= 999) {
return 1000000000000000000000;
}
if (totalTadpolez <= 1999) {
return 2000000000000000000000;
}
if (totalTadpolez <= 2999) {
return 3000000000000000000000;
}
if (totalTadpolez <= 3999) {
return 4000000000000000000000;
}
if (totalTadpolez <= 4999) {
return 5000000000000000000000;
}
if (totalTadpolez <= 5555) {
return 6000000000000000000000;
}
revert();
}
function currentBrainzCost() public view returns (uint256) {
if (totalTadpolez <= 999) {
return 1000000000000000000000;
}
if (totalTadpolez <= 1999) {
return 2000000000000000000000;
}
if (totalTadpolez <= 2999) {
return 3000000000000000000000;
}
if (totalTadpolez <= 3999) {
return 4000000000000000000000;
}
if (totalTadpolez <= 4999) {
return 5000000000000000000000;
}
if (totalTadpolez <= 5555) {
return 6000000000000000000000;
}
revert();
}
function currentBrainzCost() public view returns (uint256) {
if (totalTadpolez <= 999) {
return 1000000000000000000000;
}
if (totalTadpolez <= 1999) {
return 2000000000000000000000;
}
if (totalTadpolez <= 2999) {
return 3000000000000000000000;
}
if (totalTadpolez <= 3999) {
return 4000000000000000000000;
}
if (totalTadpolez <= 4999) {
return 5000000000000000000000;
}
if (totalTadpolez <= 5555) {
return 6000000000000000000000;
}
revert();
}
function currentBrainzCost() public view returns (uint256) {
if (totalTadpolez <= 999) {
return 1000000000000000000000;
}
if (totalTadpolez <= 1999) {
return 2000000000000000000000;
}
if (totalTadpolez <= 2999) {
return 3000000000000000000000;
}
if (totalTadpolez <= 3999) {
return 4000000000000000000000;
}
if (totalTadpolez <= 4999) {
return 5000000000000000000000;
}
if (totalTadpolez <= 5555) {
return 6000000000000000000000;
}
revert();
}
function currentBrainzCost() public view returns (uint256) {
if (totalTadpolez <= 999) {
return 1000000000000000000000;
}
if (totalTadpolez <= 1999) {
return 2000000000000000000000;
}
if (totalTadpolez <= 2999) {
return 3000000000000000000000;
}
if (totalTadpolez <= 3999) {
return 4000000000000000000000;
}
if (totalTadpolez <= 4999) {
return 5000000000000000000000;
}
if (totalTadpolez <= 5555) {
return 6000000000000000000000;
}
revert();
}
function currentBrainzCost() public view returns (uint256) {
if (totalTadpolez <= 999) {
return 1000000000000000000000;
}
if (totalTadpolez <= 1999) {
return 2000000000000000000000;
}
if (totalTadpolez <= 2999) {
return 3000000000000000000000;
}
if (totalTadpolez <= 3999) {
return 4000000000000000000000;
}
if (totalTadpolez <= 4999) {
return 5000000000000000000000;
}
if (totalTadpolez <= 5555) {
return 6000000000000000000000;
}
revert();
}
function getToadLastBred(uint256 tokenId) public view returns (uint256) {
return toadLastBred[tokenId];
}
function breedToads(uint256[] calldata _tokenIds, uint256 amount) public {
require(started, "not started");
require(totalTadpolez < totalCount, "too many tadpolez");
require(_tokenIds.length == 2, "you need 2 zombie toads to breed");
require(amount >= currentBrainzCost(), "not enough brainz");
require(IERC721(zombieToadzAddress).ownerOf(_tokenIds[0]) == _msgSender()
&& IERC721(zombieToadzAddress).ownerOf(_tokenIds[1]) == _msgSender(),
"must be the owner of both zombie toadz to breed");
require(block.timestamp - toadLastBred[_tokenIds[0]] > breedingCooldown
&& block.timestamp - toadLastBred[_tokenIds[1]] > breedingCooldown,
"one or more zombietoad is on breeding cooldown");
uint256 allowance = IERC20(brainzTokenAddress).allowance(msg.sender, address(this));
require(amount <= allowance,
string(abi.encodePacked("amount greater than allowed value of: ", allowance.toString())));
IERC20(brainzTokenAddress).transferFrom(msg.sender, address(this), currentBrainzCost());
emit MintTadpole(_msgSender(), totalTadpolez+1, 1);
_mint(_msgSender(), ++totalTadpolez);
toadLastBred[_tokenIds[0]] = block.timestamp;
toadLastBred[_tokenIds[1]] = block.timestamp;
}
function withdrawBrainz() public onlyOwner {
uint256 brainzSupply = IERC20(brainzTokenAddress).balanceOf(address(this));
IERC20(brainzTokenAddress).transfer(msg.sender, brainzSupply);
}
}
| 13,783,589 | [
1,
11890,
1049,
371,
87,
6430,
12316,
833,
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,
16351,
2285,
16659,
1385,
56,
361,
84,
790,
94,
353,
4232,
39,
27,
5340,
3098,
3245,
16,
14223,
6914,
16,
467,
654,
39,
27,
5340,
12952,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
565,
871,
490,
474,
56,
361,
84,
790,
12,
2867,
8808,
5793,
16,
2254,
5034,
787,
1190,
16,
2254,
5034,
4124,
1769,
203,
203,
203,
565,
2254,
5034,
1071,
2078,
56,
361,
84,
790,
94,
31,
203,
565,
2254,
5034,
1071,
5381,
20578,
273,
1381,
2539,
25,
31,
203,
565,
2254,
5034,
1071,
5381,
943,
4497,
273,
1728,
31,
203,
565,
1758,
1071,
998,
16659,
1385,
774,
361,
94,
1887,
31,
203,
565,
1758,
1071,
20970,
94,
1345,
1887,
31,
203,
565,
2254,
1578,
1071,
324,
15656,
310,
39,
1371,
2378,
273,
2254,
1578,
12,
28,
7507,
1769,
203,
565,
2254,
5034,
8526,
358,
361,
3024,
38,
1118,
273,
394,
2254,
5034,
8526,
12,
27982,
1769,
203,
565,
1758,
1071,
6835,
1887,
31,
203,
203,
565,
533,
1071,
1026,
3098,
31,
203,
203,
565,
1426,
3238,
5746,
31,
203,
203,
203,
203,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
16,
1758,
389,
94,
16659,
1385,
774,
361,
94,
1887,
16,
1758,
389,
70,
7596,
94,
1345,
1887,
16,
533,
3778,
1026,
3098,
67,
13,
4232,
39,
27,
5340,
12,
529,
67,
16,
3273,
67,
13,
288,
203,
3639,
1026,
3098,
273,
1026,
3098,
67,
31,
203,
3639,
998,
16659,
1385,
774,
361,
94,
1887,
273,
389,
94,
16659,
1385,
774,
361,
94,
1887,
2
]
|
./full_match/80001/0x1edb10fE0e4dd752EE7b935bDEBc7c5496DF5724/sources/wTFC_flat.sol | * @notice called when token is deposited on root chain @dev Should be callable only by ChildChainManager Should handle deposit by minting the required amount for user Make sure minting is done only by this function @param user user address for whom deposit is being done @param amount uint256 amount/ | function deposit(address user, uint256 amount)
external
override
only(DEPOSITOR_ROLE)
{
_hasSupplyChanged = true;
_mint(user, amount);
emit Deposit(user, amount);
}
| 5,642,605 | [
1,
11777,
1347,
1147,
353,
443,
1724,
329,
603,
1365,
2687,
225,
9363,
506,
4140,
1338,
635,
7451,
3893,
1318,
9363,
1640,
443,
1724,
635,
312,
474,
310,
326,
1931,
3844,
364,
729,
4344,
3071,
312,
474,
310,
353,
2731,
1338,
635,
333,
445,
225,
729,
729,
1758,
364,
600,
362,
443,
1724,
353,
3832,
2731,
225,
3844,
2254,
5034,
3844,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
443,
1724,
12,
2867,
729,
16,
2254,
5034,
3844,
13,
203,
565,
3903,
203,
565,
3849,
203,
565,
1338,
12,
1639,
28284,
916,
67,
16256,
13,
203,
565,
288,
203,
3639,
389,
5332,
3088,
1283,
5033,
273,
638,
31,
203,
3639,
389,
81,
474,
12,
1355,
16,
3844,
1769,
203,
3639,
3626,
4019,
538,
305,
12,
1355,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.8.6;
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
abstract contract IERC20WithCheckpointing {
function balanceOf(address _owner) public view virtual returns (uint256);
function balanceOfAt(address _owner, uint256 _blockNumber)
public
view
virtual
returns (uint256);
function totalSupply() public view virtual returns (uint256);
function totalSupplyAt(uint256 _blockNumber) public view virtual returns (uint256);
}
abstract contract IIncentivisedVotingLockup is IERC20WithCheckpointing {
function getLastUserPoint(address _addr)
external
view
virtual
returns (
int128 bias,
int128 slope,
uint256 ts
);
function createLock(uint256 _value, uint256 _unlockTime) external virtual;
function withdraw() external virtual;
function increaseLockAmount(uint256 _value) external virtual;
function increaseLockLength(uint256 _unlockTime) external virtual;
function eject(address _user) external virtual;
function expireContract() external virtual;
function claimReward() public virtual;
function earned(address _account) public view virtual returns (uint256);
}
interface IBoostedVaultWithLockup {
/**
* @dev Stakes a given amount of the StakingToken for the sender
* @param _amount Units of StakingToken
*/
function stake(uint256 _amount) external;
/**
* @dev Stakes a given amount of the StakingToken for a given beneficiary
* @param _beneficiary Staked tokens are credited to this address
* @param _amount Units of StakingToken
*/
function stake(address _beneficiary, uint256 _amount) external;
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function exit() external;
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function exit(uint256 _first, uint256 _last) external;
/**
* @dev Withdraws given stake amount from the pool
* @param _amount Units of the staked token to withdraw
*/
function withdraw(uint256 _amount) external;
/**
* @dev Claims only the tokens that have been immediately unlocked, not including
* those that are in the lockers.
*/
function claimReward() external;
/**
* @dev Claims all unlocked rewards for sender.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function claimRewards() external;
/**
* @dev Claims all unlocked rewards for sender. Both immediately unlocked
* rewards and also locked rewards past their time lock.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function claimRewards(uint256 _first, uint256 _last) external;
/**
* @dev Pokes a given account to reset the boost
*/
function pokeBoost(address _account) external;
/**
* @dev Gets the last applicable timestamp for this reward period
*/
function lastTimeRewardApplicable() external view returns (uint256);
/**
* @dev Calculates the amount of unclaimed rewards per token since last update,
* and sums with stored to give the new cumulative reward per token
* @return 'Reward' per staked token
*/
function rewardPerToken() external view returns (uint256);
/**
* @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this
* does NOT include the majority of rewards which will be locked up.
* @param _account User address
* @return Total reward amount earned
*/
function earned(address _account) external view returns (uint256);
/**
* @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards
* and those that have passed their time lock.
* @param _account User address
* @return amount Total units of unclaimed rewards
* @return first Index of the first userReward that has unlocked
* @return last Index of the last userReward that has unlocked
*/
function unclaimedRewards(address _account)
external
view
returns (
uint256 amount,
uint256 first,
uint256 last
);
}
interface IBoostDirector {
function getBalance(address _user) external returns (uint256);
function setDirection(
address _old,
address _new,
bool _pokeNew
) external;
function whitelistVaults(address[] calldata _vaults) external;
}
contract ModuleKeys {
// Governance
// ===========
// keccak256("Governance");
bytes32 internal constant KEY_GOVERNANCE =
0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking");
bytes32 internal constant KEY_STAKING =
0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin");
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// mStable
// =======
// keccak256("OracleHub");
bytes32 internal constant KEY_ORACLE_HUB =
0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager");
bytes32 internal constant KEY_MANAGER =
0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER =
0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken");
bytes32 internal constant KEY_META_TOKEN =
0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager");
bytes32 internal constant KEY_SAVINGS_MANAGER =
0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
// keccak256("Liquidator");
bytes32 internal constant KEY_LIQUIDATOR =
0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4;
// keccak256("InterestValidator");
bytes32 internal constant KEY_INTEREST_VALIDATOR =
0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f;
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
abstract contract ImmutableModule is ModuleKeys {
INexus public immutable nexus;
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
constructor(address _nexus) {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
_onlyGovernor();
_;
}
function _onlyGovernor() internal view {
require(msg.sender == _governor(), "Only governor can execute");
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
/**
* @dev Return Liquidator Module address from the Nexus
* @return Address of the Liquidator Module contract
*/
function _liquidator() internal view returns (address) {
return nexus.getModule(KEY_LIQUIDATOR);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
}
// SPDX-License-Identifier: AGPL-3.0-or-later
// Internal
/**
* @title BoostDirectorV2
* @author mStable
* @notice Supports the directing of balance from multiple StakedToken contracts up to X accounts
* @dev Uses a bitmap to store the id's of a given users chosen vaults in a gas efficient manner.
*/
contract BoostDirectorV2 is IBoostDirector, ImmutableModule {
event Directed(address user, address boosted);
event RedirectedBoost(address user, address boosted, address replaced);
event Whitelisted(address vaultAddress, uint8 vaultId);
event StakedTokenAdded(address token);
event StakedTokenRemoved(address token);
event BalanceDivisorChanged(uint256 newDivisor);
// Read the vMTA balance from here
IERC20[] public stakedTokenContracts;
// Whitelisted vaults set by governance (only these vaults can read balances)
uint8 private vaultCount;
// Vault address -> internal id for tracking
mapping(address => uint8) public _vaults;
// uint128 packed with up to 16 uint8's. Each uint is a vault ID
mapping(address => uint128) public _directedBitmap;
// Divisor for voting powers to make more reasonable in vault
uint256 private balanceDivisor;
/***************************************
ADMIN
****************************************/
// Simple constructor
constructor(address _nexus) ImmutableModule(_nexus) {
balanceDivisor = 12;
}
/**
* @dev Initialize function - simply sets the initial array of whitelisted vaults
*/
function initialize(address[] calldata _newVaults) external {
require(vaultCount == 0, "Already initialized");
_whitelistVaults(_newVaults);
}
/**
* @dev Adds a staked token to the list, if it does not yet exist
*/
function addStakedToken(address _stakedToken) external onlyGovernor {
uint256 len = stakedTokenContracts.length;
for (uint256 i = 0; i < len; i++) {
require(address(stakedTokenContracts[i]) != _stakedToken, "StakedToken already added");
}
stakedTokenContracts.push(IERC20(_stakedToken));
emit StakedTokenAdded(_stakedToken);
}
/**
* @dev Removes a staked token from the list
*/
function removeStakedTkoen(address _stakedToken) external onlyGovernor {
uint256 len = stakedTokenContracts.length;
for (uint256 i = 0; i < len; i++) {
// If we find it, then swap it with the last element and delete the end
if (address(stakedTokenContracts[i]) == _stakedToken) {
stakedTokenContracts[i] = stakedTokenContracts[len - 1];
stakedTokenContracts.pop();
emit StakedTokenRemoved(_stakedToken);
return;
}
}
}
/**
* @dev Sets the divisor, by which all balances will be scaled down
*/
function setBalanceDivisor(uint256 _newDivisor) external onlyGovernor {
require(_newDivisor != balanceDivisor, "No change in divisor");
require(_newDivisor < 15, "Divisor too large");
balanceDivisor = _newDivisor;
emit BalanceDivisorChanged(_newDivisor);
}
/**
* @dev Whitelist vaults - only callable by governance. Whitelists vaults, unless they
* have already been whitelisted
*/
function whitelistVaults(address[] calldata _newVaults) external override onlyGovernor {
_whitelistVaults(_newVaults);
}
/**
* @dev Takes an array of newVaults. For each, determines if it is already whitelisted.
* If not, then increment vaultCount and same the vault with new ID
*/
function _whitelistVaults(address[] calldata _newVaults) internal {
uint256 len = _newVaults.length;
require(len > 0, "Must be at least one vault");
for (uint256 i = 0; i < len; i++) {
uint8 id = _vaults[_newVaults[i]];
require(id == 0, "Vault already whitelisted");
vaultCount += 1;
_vaults[_newVaults[i]] = vaultCount;
emit Whitelisted(_newVaults[i], vaultCount);
}
}
/***************************************
Vault
****************************************/
/**
* @dev Gets the balance of a user that has been directed to the caller (a vault).
* If the user has not directed to this vault, or there are less than 6 directed,
* then add this to the list
* @param _user Address of the user for which to get balance
* @return bal Directed balance
*/
function getBalance(address _user) external override returns (uint256 bal) {
// Get vault details
uint8 id = _vaults[msg.sender];
// If vault has not been whitelisted, just return zero
if (id == 0) return 0;
// Get existing bitmap and balance
uint128 bitmap = _directedBitmap[_user];
uint256 len = stakedTokenContracts.length;
for (uint256 i = 0; i < len; i++) {
bal += stakedTokenContracts[i].balanceOf(_user);
}
bal /= balanceDivisor;
(bool isWhitelisted, uint8 count, ) = _indexExists(bitmap, id);
if (isWhitelisted) return bal;
if (count < 6) {
_directedBitmap[_user] = _direct(bitmap, count, id);
emit Directed(_user, msg.sender);
return bal;
}
if (count >= 6) return 0;
}
/**
* @dev Directs rewards to a vault, and removes them from the old vault. Provided
* that old is active and the new vault is whitelisted.
* @param _old Address of the old vault that will no longer get boosted
* @param _new Address of the new vault that will get boosted
* @param _pokeNew Bool to say if we should poke the boost on the new vault
*/
function setDirection(
address _old,
address _new,
bool _pokeNew
) external override {
uint8 idOld = _vaults[_old];
uint8 idNew = _vaults[_new];
require(idOld > 0 && idNew > 0, "Vaults not whitelisted");
uint128 bitmap = _directedBitmap[msg.sender];
(bool isWhitelisted, uint8 count, uint8 pos) = _indexExists(bitmap, idOld);
require(isWhitelisted && count >= 6, "No need to replace old");
_directedBitmap[msg.sender] = _direct(bitmap, pos, idNew);
IBoostedVaultWithLockup(_old).pokeBoost(msg.sender);
if (_pokeNew) {
IBoostedVaultWithLockup(_new).pokeBoost(msg.sender);
}
emit RedirectedBoost(msg.sender, _new, _old);
}
/**
* @dev Resets the bitmap given the new _id for _pos. Takes each uint8 in seperate and re-compiles
*/
function _direct(
uint128 _bitmap,
uint8 _pos,
uint8 _id
) internal pure returns (uint128 newMap) {
// bitmap = ... 00000000 00000000 00000011 00001010
// pos = 1, id = 1 = 00000001
// step = ... 00000000 00000000 00000001 00000000
uint8 id;
uint128 step;
for (uint8 i = 0; i < 6; i++) {
unchecked {
// id is either the one that is passed, or existing
id = _pos == i ? _id : uint8(_bitmap >> (i * 8));
step = uint128(uint128(id) << (i * 8));
}
newMap |= step;
}
}
/**
* @dev Given a 128 bit bitmap packed with 8 bit ids, should be able to filter for specific ids by moving
* the bitmap gradually to the right and reading each 8 bit section as a uint8.
*/
function _indexExists(uint128 _bitmap, uint8 _target)
internal
pure
returns (
bool isWhitelisted,
uint8 count,
uint8 pos
)
{
// bitmap = ... 00000000 00000000 00000011 00001010 // positions 1 and 2 have ids 10 and 6 respectively
// e.g.
// i = 1: bitmap moves 8 bits to the right
// bitmap = ... 00000000 00000000 00000000 00000011 // reading uint8 should return 6
uint8 id;
for (uint8 i = 0; i < 6; i++) {
unchecked {
id = uint8(_bitmap >> (i * 8));
}
if (id > 0) count += 1;
if (id == _target) {
isWhitelisted = true;
pos = i;
}
}
}
} | * @dev Removes a staked token from the list/ If we find it, then swap it with the last element and delete the end | function removeStakedTkoen(address _stakedToken) external onlyGovernor {
uint256 len = stakedTokenContracts.length;
for (uint256 i = 0; i < len; i++) {
if (address(stakedTokenContracts[i]) == _stakedToken) {
stakedTokenContracts[i] = stakedTokenContracts[len - 1];
stakedTokenContracts.pop();
emit StakedTokenRemoved(_stakedToken);
return;
}
}
}
| 638,710 | [
1,
6220,
279,
384,
9477,
1147,
628,
326,
666,
19,
971,
732,
1104,
518,
16,
1508,
7720,
518,
598,
326,
1142,
930,
471,
1430,
326,
679,
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,
1206,
510,
9477,
56,
28179,
275,
12,
2867,
389,
334,
9477,
1345,
13,
3903,
1338,
43,
1643,
29561,
288,
203,
3639,
2254,
5034,
562,
273,
384,
9477,
1345,
20723,
18,
2469,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
562,
31,
277,
27245,
288,
203,
5411,
309,
261,
2867,
12,
334,
9477,
1345,
20723,
63,
77,
5717,
422,
389,
334,
9477,
1345,
13,
288,
203,
7734,
384,
9477,
1345,
20723,
63,
77,
65,
273,
384,
9477,
1345,
20723,
63,
1897,
300,
404,
15533,
203,
7734,
384,
9477,
1345,
20723,
18,
5120,
5621,
203,
7734,
3626,
934,
9477,
1345,
10026,
24899,
334,
9477,
1345,
1769,
203,
7734,
327,
31,
203,
5411,
289,
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
]
|
./full_match/1/0xA0C20eef415ed68a16215e061821D6ad24767Db1/sources/lib/tl-sol-tools/src/upgradeable/royalties/EIP2981TLUpgradeable.sol | @inheritdoc ERC165Upgradeable | function supportsInterface(bytes4 interfaceId) public view virtual override (ERC165Upgradeable) returns (bool) {
return interfaceId == type(IEIP2981).interfaceId || ERC165Upgradeable.supportsInterface(interfaceId);
}
External View Functions
| 8,401,532 | [
1,
36,
10093,
4232,
39,
28275,
10784,
429,
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,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
261,
654,
39,
28275,
10784,
429,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
1560,
548,
422,
618,
12,
8732,
2579,
5540,
11861,
2934,
5831,
548,
747,
4232,
39,
28275,
10784,
429,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
18701,
11352,
4441,
15486,
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
]
|
// Verified using https://dapp.tools
// hevm: flattened sources of src/GebProxySaviourActions.sol
pragma solidity =0.6.7 >=0.6.7;
////// lib/geb-proxy-registry/lib/ds-proxy/lib/ds-auth/src/auth.sol
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
/* pragma solidity >=0.6.7; */
interface DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) external view returns (bool);
}
abstract contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
virtual
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
virtual
public
auth
{
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized");
_;
}
function isAuthorized(address src, bytes4 sig) virtual internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
////// src/GebProxyActions.sol
/// GebProxyActions.sol
// Copyright (C) 2018-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.7; */
/* import "ds-auth/auth.sol"; */
abstract contract CollateralLike_3 {
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public;
function transferFrom(address, address, uint) virtual public;
function deposit() virtual public payable;
function withdraw(uint) virtual public;
}
abstract contract ManagerLike {
function safeCan(address, uint, address) virtual public view returns (uint);
function collateralTypes(uint) virtual public view returns (bytes32);
function ownsSAFE(uint) virtual public view returns (address);
function safes(uint) virtual public view returns (address);
function safeEngine() virtual public view returns (address);
function openSAFE(bytes32, address) virtual public returns (uint);
function transferSAFEOwnership(uint, address) virtual public;
function allowSAFE(uint, address, uint) virtual public;
function allowHandler(address, uint) virtual public;
function modifySAFECollateralization(uint, int, int) virtual public;
function transferCollateral(uint, address, uint) virtual public;
function transferInternalCoins(uint, address, uint) virtual public;
function quitSystem(uint, address) virtual public;
function enterSystem(address, uint) virtual public;
function moveSAFE(uint, uint) virtual public;
function protectSAFE(uint, address, address) virtual public;
}
abstract contract SAFEEngineLike_15 {
function canModifySAFE(address, address) virtual public view returns (uint);
function collateralTypes(bytes32) virtual public view returns (uint, uint, uint, uint, uint);
function coinBalance(address) virtual public view returns (uint);
function safes(bytes32, address) virtual public view returns (uint, uint);
function modifySAFECollateralization(bytes32, address, address, address, int, int) virtual public;
function approveSAFEModification(address) virtual public;
function transferInternalCoins(address, address, uint) virtual public;
}
abstract contract CollateralJoinLike_2 {
function decimals() virtual public returns (uint);
function collateral() virtual public returns (CollateralLike_3);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
abstract contract GNTJoinLike {
function bags(address) virtual public view returns (address);
function make(address) virtual public returns (address);
}
abstract contract DSTokenLike_3 {
function balanceOf(address) virtual public view returns (uint);
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public returns (bool);
function transferFrom(address, address, uint) virtual public returns (bool);
}
abstract contract WethLike {
function balanceOf(address) virtual public view returns (uint);
function approve(address, uint) virtual public;
function transfer(address, uint) virtual public;
function transferFrom(address, address, uint) virtual public;
function deposit() virtual public payable;
function withdraw(uint) virtual public;
}
abstract contract CoinJoinLike_3 {
function safeEngine() virtual public returns (SAFEEngineLike_15);
function systemCoin() virtual public returns (DSTokenLike_3);
function join(address, uint) virtual public payable;
function exit(address, uint) virtual public;
}
abstract contract ApproveSAFEModificationLike {
function approveSAFEModification(address) virtual public;
function denySAFEModification(address) virtual public;
}
abstract contract GlobalSettlementLike_3 {
function collateralCashPrice(bytes32) virtual public view returns (uint);
function redeemCollateral(bytes32, uint) virtual public;
function freeCollateral(bytes32) virtual public;
function prepareCoinsForRedeeming(uint) virtual public;
function processSAFE(bytes32, address) virtual public;
}
abstract contract TaxCollectorLike {
function taxSingle(bytes32) virtual public returns (uint);
}
abstract contract CoinSavingsAccountLike_2 {
function savings(address) virtual public view returns (uint);
function updateAccumulatedRate() virtual public returns (uint);
function deposit(uint) virtual public;
function withdraw(uint) virtual public;
}
abstract contract ProxyRegistryLike {
function proxies(address) virtual public view returns (address);
function build(address) virtual public returns (address);
}
abstract contract ProxyLike {
function owner() virtual public view returns (address);
}
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// WARNING: These functions meant to be used as a a library for a DSProxy. Some are unsafe if you call them directly.
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
contract Common {
uint256 constant RAY = 10 ** 27;
// Internal functions
function multiply(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
function _coinJoin_join(address apt, address safeHandler, uint wad) internal {
// Approves adapter to take the COIN amount
CoinJoinLike_3(apt).systemCoin().approve(apt, wad);
// Joins COIN into the safeEngine
CoinJoinLike_3(apt).join(safeHandler, wad);
}
// Public functions
function coinJoin_join(address apt, address safeHandler, uint wad) public {
// Gets COIN from the user's wallet
CoinJoinLike_3(apt).systemCoin().transferFrom(msg.sender, address(this), wad);
_coinJoin_join(apt, safeHandler, wad);
}
}
contract BasicActions is Common {
// Internal functions
/// @notice Safe subtraction
/// @dev Reverts on overflows
function subtract(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "sub-overflow");
}
/// @notice Safe conversion uint -> int
/// @dev Reverts on overflows
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
/// @notice Converts a wad (18 decimal places) to rad (45 decimal places)
function toRad(uint wad) internal pure returns (uint rad) {
rad = multiply(wad, 10 ** 27);
}
function convertTo18(address collateralJoin, uint256 amt) internal returns (uint256 wad) {
// For those collaterals that have other than 18 decimals precision we need to do the conversion before passing to modifySAFECollateralization function
// Adapters will automatically handle the difference of precision
uint decimals = CollateralJoinLike_2(collateralJoin).decimals();
wad = amt;
if (decimals < 18) {
wad = multiply(
amt,
10 ** (18 - decimals)
);
} else if (decimals > 18) {
wad = amt / 10 ** (decimals - 18);
}
}
/// @notice Gets delta debt generated (Total Safe debt minus available safeHandler COIN balance)
/// @param safeEngine address
/// @param taxCollector address
/// @param safeHandler address
/// @param collateralType bytes32
/// @return deltaDebt
function _getGeneratedDeltaDebt(
address safeEngine,
address taxCollector,
address safeHandler,
bytes32 collateralType,
uint wad
) internal returns (int deltaDebt) {
// Updates stability fee rate
uint rate = TaxCollectorLike(taxCollector).taxSingle(collateralType);
require(rate > 0, "invalid-collateral-type");
// Gets COIN balance of the handler in the safeEngine
uint coin = SAFEEngineLike_15(safeEngine).coinBalance(safeHandler);
// If there was already enough COIN in the safeEngine balance, just exits it without adding more debt
if (coin < multiply(wad, RAY)) {
// Calculates the needed deltaDebt so together with the existing coins in the safeEngine is enough to exit wad amount of COIN tokens
deltaDebt = toInt(subtract(multiply(wad, RAY), coin) / rate);
// This is neeeded due lack of precision. It might need to sum an extra deltaDebt wei (for the given COIN wad amount)
deltaDebt = multiply(uint(deltaDebt), rate) < multiply(wad, RAY) ? deltaDebt + 1 : deltaDebt;
}
}
/// @notice Gets repaid delta debt generated (rate adjusted debt)
/// @param safeEngine address
/// @param coin uint amount
/// @param safe uint - safeId
/// @param collateralType bytes32
/// @return deltaDebt
function _getRepaidDeltaDebt(
address safeEngine,
uint coin,
address safe,
bytes32 collateralType
) internal view returns (int deltaDebt) {
// Gets actual rate from the safeEngine
(, uint rate,,,) = SAFEEngineLike_15(safeEngine).collateralTypes(collateralType);
require(rate > 0, "invalid-collateral-type");
// Gets actual generatedDebt value of the safe
(, uint generatedDebt) = SAFEEngineLike_15(safeEngine).safes(collateralType, safe);
// Uses the whole coin balance in the safeEngine to reduce the debt
deltaDebt = toInt(coin / rate);
// Checks the calculated deltaDebt is not higher than safe.generatedDebt (total debt), otherwise uses its value
deltaDebt = uint(deltaDebt) <= generatedDebt ? - deltaDebt : - toInt(generatedDebt);
}
/// @notice Gets repaid debt (rate adjusted rate minus COIN balance available in usr's address)
/// @param safeEngine address
/// @param usr address
/// @param safe uint
/// @param collateralType address
/// @return wad
function _getRepaidAlDebt(
address safeEngine,
address usr,
address safe,
bytes32 collateralType
) internal view returns (uint wad) {
// Gets actual rate from the safeEngine
(, uint rate,,,) = SAFEEngineLike_15(safeEngine).collateralTypes(collateralType);
// Gets actual generatedDebt value of the safe
(, uint generatedDebt) = SAFEEngineLike_15(safeEngine).safes(collateralType, safe);
// Gets actual coin amount in the safe
uint coin = SAFEEngineLike_15(safeEngine).coinBalance(usr);
uint rad = subtract(multiply(generatedDebt, rate), coin);
wad = rad / RAY;
// If the rad precision has some dust, it will need to request for 1 extra wad wei
wad = multiply(wad, RAY) < rad ? wad + 1 : wad;
}
/// @notice Generates Debt (and sends coin balance to address to)
/// @param manager address
/// @param taxCollector address
/// @param coinJoin address
/// @param safe uint
/// @param wad uint - amount of debt to be generated
/// @param to address - receiver of the balance of generated COIN
function _generateDebt(address manager, address taxCollector, address coinJoin, uint safe, uint wad, address to) internal {
address safeHandler = ManagerLike(manager).safes(safe);
address safeEngine = ManagerLike(manager).safeEngine();
bytes32 collateralType = ManagerLike(manager).collateralTypes(safe);
// Generates debt in the SAFE
modifySAFECollateralization(manager, safe, 0, _getGeneratedDeltaDebt(safeEngine, taxCollector, safeHandler, collateralType, wad));
// Moves the COIN amount (balance in the safeEngine in rad) to proxy's address
transferInternalCoins(manager, safe, address(this), toRad(wad));
// Allows adapter to access to proxy's COIN balance in the safeEngine
if (SAFEEngineLike_15(safeEngine).canModifySAFE(address(this), address(coinJoin)) == 0) {
SAFEEngineLike_15(safeEngine).approveSAFEModification(coinJoin);
}
// Exits COIN to this contract
CoinJoinLike_3(coinJoin).exit(to, wad);
}
/// @notice Generates Debt (and sends coin balance to address to)
/// @param manager address
/// @param ethJoin address
/// @param safe uint
/// @param value uint - amount of ETH to be locked in the Safe.
/// @dev Proxy needs to have enough balance (> value), public functions should handle this.
function _lockETH(
address manager,
address ethJoin,
uint safe,
uint value
) internal {
// Receives ETH amount, converts it to WETH and joins it into the safeEngine
ethJoin_join(ethJoin, address(this), value);
// Locks WETH amount into the SAFE
SAFEEngineLike_15(ManagerLike(manager).safeEngine()).modifySAFECollateralization(
ManagerLike(manager).collateralTypes(safe),
ManagerLike(manager).safes(safe),
address(this),
address(this),
toInt(value),
0
);
}
/// @notice Repays debt
/// @param manager address
/// @param coinJoin address
/// @param safe uint
/// @param wad uint - amount of debt to be repayed
function _repayDebt(
address manager,
address coinJoin,
uint safe,
uint wad,
bool transferFromCaller
) internal {
address safeEngine = ManagerLike(manager).safeEngine();
address safeHandler = ManagerLike(manager).safes(safe);
bytes32 collateralType = ManagerLike(manager).collateralTypes(safe);
address own = ManagerLike(manager).ownsSAFE(safe);
if (own == address(this) || ManagerLike(manager).safeCan(own, safe, address(this)) == 1) {
// Joins COIN amount into the safeEngine
if (transferFromCaller) coinJoin_join(coinJoin, safeHandler, wad);
else _coinJoin_join(coinJoin, safeHandler, wad);
// // Paybacks debt to the SAFE
modifySAFECollateralization(manager, safe, 0, _getRepaidDeltaDebt(safeEngine, SAFEEngineLike_15(safeEngine).coinBalance(safeHandler), safeHandler, collateralType));
} else {
// Joins COIN amount into the safeEngine
if (transferFromCaller) coinJoin_join(coinJoin, address(this), wad);
else _coinJoin_join(coinJoin, address(this), wad);
// Paybacks debt to the SAFE
SAFEEngineLike_15(safeEngine).modifySAFECollateralization(
collateralType,
safeHandler,
address(this),
address(this),
0,
_getRepaidDeltaDebt(safeEngine, wad * RAY, safeHandler, collateralType)
);
}
}
/// @notice Repays debt and frees collateral ETH
/// @param manager address
/// @param ethJoin address
/// @param coinJoin address
/// @param safe uint
/// @param collateralWad uint - amount of ETH to free
/// @param deltaWad uint - amount of debt to be repayed
/// @param transferFromCaller True if transferring coin from caller, false if balance in the proxy
function _repayDebtAndFreeETH(
address manager,
address ethJoin,
address coinJoin,
uint safe,
uint collateralWad,
uint deltaWad,
bool transferFromCaller
) internal {
address safeHandler = ManagerLike(manager).safes(safe);
// Joins COIN amount into the safeEngine
if (transferFromCaller) coinJoin_join(coinJoin, safeHandler, deltaWad);
else _coinJoin_join(coinJoin, safeHandler, deltaWad);
// Paybacks debt to the SAFE and unlocks WETH amount from it
modifySAFECollateralization(
manager,
safe,
-toInt(collateralWad),
_getRepaidDeltaDebt(ManagerLike(manager).safeEngine(), SAFEEngineLike_15(ManagerLike(manager).safeEngine()).coinBalance(safeHandler), safeHandler, ManagerLike(manager).collateralTypes(safe))
);
// Moves the amount from the SAFE handler to proxy's address
transferCollateral(manager, safe, address(this), collateralWad);
// Exits WETH amount to proxy address as a token
CollateralJoinLike_2(ethJoin).exit(address(this), collateralWad);
// Converts WETH to ETH
CollateralJoinLike_2(ethJoin).collateral().withdraw(collateralWad);
}
// Public functions
/// @notice ERC20 transfer
/// @param collateral address - address of ERC20 collateral
/// @param dst address - Transfer destination
/// @param amt address - Amount to transfer
function transfer(address collateral, address dst, uint amt) external {
CollateralLike_3(collateral).transfer(dst, amt);
}
/// @notice Joins the system with the full msg.value
/// @param apt address - Address of the adapter
/// @param safe uint - Safe Id
function ethJoin_join(address apt, address safe) external payable {
ethJoin_join(apt, safe, msg.value);
}
/// @notice Joins the system with the a specified value
/// @param apt address - Address of the adapter
/// @param safe uint - Safe Id
/// @param value uint - Value to join
function ethJoin_join(address apt, address safe, uint value) public payable {
// Wraps ETH in WETH
CollateralJoinLike_2(apt).collateral().deposit{value: value}();
// Approves adapter to take the WETH amount
CollateralJoinLike_2(apt).collateral().approve(address(apt), value);
// Joins WETH collateral into the safeEngine
CollateralJoinLike_2(apt).join(safe, value);
}
/// @notice Approves an address to modify the Safe
/// @param safeEngine address
/// @param usr address - Address allowed to modify Safe
function approveSAFEModification(
address safeEngine,
address usr
) external {
ApproveSAFEModificationLike(safeEngine).approveSAFEModification(usr);
}
/// @notice Denies an address to modify the Safe
/// @param safeEngine address
/// @param usr address - Address disallowed to modify Safe
function denySAFEModification(
address safeEngine,
address usr
) external {
ApproveSAFEModificationLike(safeEngine).denySAFEModification(usr);
}
/// @notice Opens a brand new Safe
/// @param manager address - Safe Manager
/// @param collateralType bytes32 - collateral type
/// @param usr address - Owner of the safe
function openSAFE(
address manager,
bytes32 collateralType,
address usr
) public returns (uint safe) {
safe = ManagerLike(manager).openSAFE(collateralType, usr);
}
/// @notice Transfer the ownership of a proxy owned Safe
/// @param manager address - Safe Manager
/// @param safe uint - Safe Id
/// @param usr address - Owner of the safe
function transferSAFEOwnership(
address manager,
uint safe,
address usr
) public {
ManagerLike(manager).transferSAFEOwnership(safe, usr);
}
/// @notice Transfer the ownership to a new proxy owned by a different address
/// @param proxyRegistry address - Safe Manager
/// @param manager address - Safe Manager
/// @param safe uint - Safe Id
/// @param dst address - Owner of the new proxy
function transferSAFEOwnershipToProxy(
address proxyRegistry,
address manager,
uint safe,
address dst
) external {
// Gets actual proxy address
address proxy = ProxyRegistryLike(proxyRegistry).proxies(dst);
// Checks if the proxy address already existed and dst address is still the owner
if (proxy == address(0) || ProxyLike(proxy).owner() != dst) {
uint csize;
assembly {
csize := extcodesize(dst)
}
// We want to avoid creating a proxy for a contract address that might not be able to handle proxies, then losing the SAFE
require(csize == 0, "dst-is-a-contract");
// Creates the proxy for the dst address
proxy = ProxyRegistryLike(proxyRegistry).build(dst);
}
// Transfers SAFE to the dst proxy
transferSAFEOwnership(manager, safe, proxy);
}
/// @notice Allow/disallow a usr address to manage the safe
/// @param manager address - Safe Manager
/// @param safe uint - Safe Id
/// @param usr address - usr address
/// uint ok - 1 for allowed
function allowSAFE(
address manager,
uint safe,
address usr,
uint ok
) external {
ManagerLike(manager).allowSAFE(safe, usr, ok);
}
/// @notice Allow/disallow a usr address to quit to the sender handler
/// @param manager address - Safe Manager
/// @param usr address - usr address
/// uint ok - 1 for allowed
function allowHandler(
address manager,
address usr,
uint ok
) external {
ManagerLike(manager).allowHandler(usr, ok);
}
/// @notice Transfer wad amount of safe collateral from the safe address to a dst address.
/// @param manager address - Safe Manager
/// @param safe uint - Safe Id
/// @param dst address - destination address
/// uint wad - amount
function transferCollateral(
address manager,
uint safe,
address dst,
uint wad
) public {
ManagerLike(manager).transferCollateral(safe, dst, wad);
}
/// @notice Transfer rad amount of COIN from the safe address to a dst address.
/// @param manager address - Safe Manager
/// @param safe uint - Safe Id
/// @param dst address - destination address
/// uint rad - amount
function transferInternalCoins(
address manager,
uint safe,
address dst,
uint rad
) public {
ManagerLike(manager).transferInternalCoins(safe, dst, rad);
}
/// @notice Modify a SAFE's collateralization ratio while keeping the generated COIN or collateral freed in the SAFE handler address.
/// @param manager address - Safe Manager
/// @param safe uint - Safe Id
/// @param deltaCollateral - int
/// @param deltaDebt - int
function modifySAFECollateralization(
address manager,
uint safe,
int deltaCollateral,
int deltaDebt
) public {
ManagerLike(manager).modifySAFECollateralization(safe, deltaCollateral, deltaDebt);
}
/// @notice Quit the system, migrating the safe (lockedCollateral, generatedDebt) to a different dst handler
/// @param manager address - Safe Manager
/// @param safe uint - Safe Id
/// @param dst - destination handler
function quitSystem(
address manager,
uint safe,
address dst
) external {
ManagerLike(manager).quitSystem(safe, dst);
}
/// @notice Import a position from src handler to the handler owned by safe
/// @param manager address - Safe Manager
/// @param src - source handler
/// @param safe uint - Safe Id
function enterSystem(
address manager,
address src,
uint safe
) external {
ManagerLike(manager).enterSystem(src, safe);
}
/// @notice Move a position from safeSrc handler to the safeDst handler
/// @param manager address - Safe Manager
/// @param safeSrc uint - Source Safe Id
/// @param safeDst uint - Destination Safe Id
function moveSAFE(
address manager,
uint safeSrc,
uint safeDst
) external {
ManagerLike(manager).moveSAFE(safeSrc, safeDst);
}
/// @notice Lock ETH (msg.value) as collateral in safe
/// @param manager address - Safe Manager
/// @param ethJoin address
/// @param safe uint - Safe Id
function lockETH(
address manager,
address ethJoin,
uint safe
) public payable {
_lockETH(manager, ethJoin, safe, msg.value);
}
/// @notice Free ETH (wad) from safe and sends it to msg.sender
/// @param manager address - Safe Manager
/// @param ethJoin address
/// @param safe uint - Safe Id
/// @param wad uint - Amount
function freeETH(
address manager,
address ethJoin,
uint safe,
uint wad
) public {
// Unlocks WETH amount from the SAFE
modifySAFECollateralization(manager, safe, -toInt(wad), 0);
// Moves the amount from the SAFE handler to proxy's address
transferCollateral(manager, safe, address(this), wad);
// Exits WETH amount to proxy address as a token
CollateralJoinLike_2(ethJoin).exit(address(this), wad);
// Converts WETH to ETH
CollateralJoinLike_2(ethJoin).collateral().withdraw(wad);
// Sends ETH back to the user's wallet
msg.sender.transfer(wad);
}
/// @notice Exits ETH (wad) from balance available in the handler
/// @param manager address - Safe Manager
/// @param ethJoin address
/// @param safe uint - Safe Id
/// @param wad uint - Amount
function exitETH(
address manager,
address ethJoin,
uint safe,
uint wad
) external {
// Moves the amount from the SAFE handler to proxy's address
transferCollateral(manager, safe, address(this), wad);
// Exits WETH amount to proxy address as a token
CollateralJoinLike_2(ethJoin).exit(address(this), wad);
// Converts WETH to ETH
CollateralJoinLike_2(ethJoin).collateral().withdraw(wad);
// Sends ETH back to the user's wallet
msg.sender.transfer(wad);
}
/// @notice Generates debt and sends COIN amount to msg.sender
/// @param manager address
/// @param taxCollector address
/// @param coinJoin address
/// @param safe uint - Safe Id
/// @param wad uint - Amount
function generateDebt(
address manager,
address taxCollector,
address coinJoin,
uint safe,
uint wad
) public {
_generateDebt(manager, taxCollector, coinJoin, safe, wad, msg.sender);
}
/// @notice Repays debt
/// @param manager address
/// @param coinJoin address
/// @param safe uint - Safe Id
/// @param wad uint - Amount
function repayDebt(
address manager,
address coinJoin,
uint safe,
uint wad
) public {
_repayDebt(manager, coinJoin, safe, wad, true);
}
/// @notice Locks Eth, generates debt and sends COIN amount (deltaWad) to msg.sender
/// @param manager address
/// @param taxCollector address
/// @param ethJoin address
/// @param coinJoin address
/// @param safe uint - Safe Id
/// @param deltaWad uint - Amount
function lockETHAndGenerateDebt(
address manager,
address taxCollector,
address ethJoin,
address coinJoin,
uint safe,
uint deltaWad
) public payable {
_lockETH(manager, ethJoin, safe, msg.value);
_generateDebt(manager, taxCollector, coinJoin, safe, deltaWad, msg.sender);
}
/// @notice Opens Safe, locks Eth, generates debt and sends COIN amount (deltaWad) to msg.sender
/// @param manager address
/// @param taxCollector address
/// @param ethJoin address
/// @param coinJoin address
/// @param deltaWad uint - Amount
function openLockETHAndGenerateDebt(
address manager,
address taxCollector,
address ethJoin,
address coinJoin,
bytes32 collateralType,
uint deltaWad
) external payable returns (uint safe) {
safe = openSAFE(manager, collateralType, address(this));
lockETHAndGenerateDebt(manager, taxCollector, ethJoin, coinJoin, safe, deltaWad);
}
/// @notice Repays debt and frees ETH (sends it to msg.sender)
/// @param manager address
/// @param ethJoin address
/// @param coinJoin address
/// @param safe uint - Safe Id
/// @param collateralWad uint - Amount of collateral to free
/// @param deltaWad uint - Amount of debt to repay
function repayDebtAndFreeETH(
address manager,
address ethJoin,
address coinJoin,
uint safe,
uint collateralWad,
uint deltaWad
) external {
_repayDebtAndFreeETH(manager, ethJoin, coinJoin, safe, collateralWad, deltaWad, true);
// Sends ETH back to the user's wallet
msg.sender.transfer(collateralWad);
}
}
contract GebProxyActions is BasicActions {
function tokenCollateralJoin_join(address apt, address safe, uint amt, bool transferFrom) public {
// Only executes for tokens that have approval/transferFrom implementation
if (transferFrom) {
// Gets token from the user's wallet
CollateralJoinLike_2(apt).collateral().transferFrom(msg.sender, address(this), amt);
// Approves adapter to take the token amount
CollateralJoinLike_2(apt).collateral().approve(apt, amt);
}
// Joins token collateral into the safeEngine
CollateralJoinLike_2(apt).join(safe, amt);
}
function protectSAFE(
address manager,
uint safe,
address liquidationEngine,
address saviour
) public {
ManagerLike(manager).protectSAFE(safe, liquidationEngine, saviour);
}
function makeCollateralBag(
address collateralJoin
) public returns (address bag) {
bag = GNTJoinLike(collateralJoin).make(address(this));
}
function safeLockETH(
address manager,
address ethJoin,
uint safe,
address owner
) public payable {
require(ManagerLike(manager).ownsSAFE(safe) == owner, "owner-missmatch");
lockETH(manager, ethJoin, safe);
}
function lockTokenCollateral(
address manager,
address collateralJoin,
uint safe,
uint amt,
bool transferFrom
) public {
// Takes token amount from user's wallet and joins into the safeEngine
tokenCollateralJoin_join(collateralJoin, address(this), amt, transferFrom);
// Locks token amount into the SAFE
SAFEEngineLike_15(ManagerLike(manager).safeEngine()).modifySAFECollateralization(
ManagerLike(manager).collateralTypes(safe),
ManagerLike(manager).safes(safe),
address(this),
address(this),
toInt(convertTo18(collateralJoin, amt)),
0
);
}
function safeLockTokenCollateral(
address manager,
address collateralJoin,
uint safe,
uint amt,
bool transferFrom,
address owner
) public {
require(ManagerLike(manager).ownsSAFE(safe) == owner, "owner-missmatch");
lockTokenCollateral(manager, collateralJoin, safe, amt, transferFrom);
}
function freeTokenCollateral(
address manager,
address collateralJoin,
uint safe,
uint amt
) public {
uint wad = convertTo18(collateralJoin, amt);
// Unlocks token amount from the SAFE
modifySAFECollateralization(manager, safe, -toInt(wad), 0);
// Moves the amount from the SAFE handler to proxy's address
transferCollateral(manager, safe, address(this), wad);
// Exits token amount to the user's wallet as a token
CollateralJoinLike_2(collateralJoin).exit(msg.sender, amt);
}
function exitTokenCollateral(
address manager,
address collateralJoin,
uint safe,
uint amt
) public {
// Moves the amount from the SAFE handler to proxy's address
transferCollateral(manager, safe, address(this), convertTo18(collateralJoin, amt));
// Exits token amount to the user's wallet as a token
CollateralJoinLike_2(collateralJoin).exit(msg.sender, amt);
}
function generateDebtAndProtectSAFE(
address manager,
address taxCollector,
address coinJoin,
uint safe,
uint wad,
address liquidationEngine,
address saviour
) external {
generateDebt(manager, taxCollector, coinJoin, safe, wad);
protectSAFE(manager, safe, liquidationEngine, saviour);
}
function safeRepayDebt(
address manager,
address coinJoin,
uint safe,
uint wad,
address owner
) public {
require(ManagerLike(manager).ownsSAFE(safe) == owner, "owner-missmatch");
repayDebt(manager, coinJoin, safe, wad);
}
function repayAllDebt(
address manager,
address coinJoin,
uint safe
) public {
address safeEngine = ManagerLike(manager).safeEngine();
address safeHandler = ManagerLike(manager).safes(safe);
bytes32 collateralType = ManagerLike(manager).collateralTypes(safe);
(, uint generatedDebt) = SAFEEngineLike_15(safeEngine).safes(collateralType, safeHandler);
address own = ManagerLike(manager).ownsSAFE(safe);
if (own == address(this) || ManagerLike(manager).safeCan(own, safe, address(this)) == 1) {
// Joins COIN amount into the safeEngine
coinJoin_join(coinJoin, safeHandler, _getRepaidAlDebt(safeEngine, safeHandler, safeHandler, collateralType));
// Paybacks debt to the SAFE
modifySAFECollateralization(manager, safe, 0, -int(generatedDebt));
} else {
// Joins COIN amount into the safeEngine
coinJoin_join(coinJoin, address(this), _getRepaidAlDebt(safeEngine, address(this), safeHandler, collateralType));
// Paybacks debt to the SAFE
SAFEEngineLike_15(safeEngine).modifySAFECollateralization(
collateralType,
safeHandler,
address(this),
address(this),
0,
-int(generatedDebt)
);
}
}
function safeRepayAllDebt(
address manager,
address coinJoin,
uint safe,
address owner
) public {
require(ManagerLike(manager).ownsSAFE(safe) == owner, "owner-missmatch");
repayAllDebt(manager, coinJoin, safe);
}
function openLockETHGenerateDebtAndProtectSAFE(
address manager,
address taxCollector,
address ethJoin,
address coinJoin,
bytes32 collateralType,
uint deltaWad,
address liquidationEngine,
address saviour
) public payable returns (uint safe) {
safe = openSAFE(manager, collateralType, address(this));
lockETHAndGenerateDebt(manager, taxCollector, ethJoin, coinJoin, safe, deltaWad);
protectSAFE(manager, safe, liquidationEngine, saviour);
}
function lockTokenCollateralAndGenerateDebt(
address manager,
address taxCollector,
address collateralJoin,
address coinJoin,
uint safe,
uint collateralAmount,
uint deltaWad,
bool transferFrom
) public {
address safeHandler = ManagerLike(manager).safes(safe);
address safeEngine = ManagerLike(manager).safeEngine();
bytes32 collateralType = ManagerLike(manager).collateralTypes(safe);
// Takes token amount from user's wallet and joins into the safeEngine
tokenCollateralJoin_join(collateralJoin, safeHandler, collateralAmount, transferFrom);
// Locks token amount into the SAFE and generates debt
modifySAFECollateralization(manager, safe, toInt(convertTo18(collateralJoin, collateralAmount)), _getGeneratedDeltaDebt(safeEngine, taxCollector, safeHandler, collateralType, deltaWad));
// Moves the COIN amount (balance in the safeEngine in rad) to proxy's address
transferInternalCoins(manager, safe, address(this), toRad(deltaWad));
// Allows adapter to access to proxy's COIN balance in the safeEngine
if (SAFEEngineLike_15(safeEngine).canModifySAFE(address(this), address(coinJoin)) == 0) {
SAFEEngineLike_15(safeEngine).approveSAFEModification(coinJoin);
}
// Exits COIN to the user's wallet as a token
CoinJoinLike_3(coinJoin).exit(msg.sender, deltaWad);
}
function lockTokenCollateralGenerateDebtAndProtectSAFE(
address manager,
address taxCollector,
address collateralJoin,
address coinJoin,
uint safe,
uint collateralAmount,
uint deltaWad,
bool transferFrom,
address liquidationEngine,
address saviour
) public {
lockTokenCollateralAndGenerateDebt(
manager,
taxCollector,
collateralJoin,
coinJoin,
safe,
collateralAmount,
deltaWad,
transferFrom
);
protectSAFE(manager, safe, liquidationEngine, saviour);
}
function openLockTokenCollateralAndGenerateDebt(
address manager,
address taxCollector,
address collateralJoin,
address coinJoin,
bytes32 collateralType,
uint collateralAmount,
uint deltaWad,
bool transferFrom
) public returns (uint safe) {
safe = openSAFE(manager, collateralType, address(this));
lockTokenCollateralAndGenerateDebt(manager, taxCollector, collateralJoin, coinJoin, safe, collateralAmount, deltaWad, transferFrom);
}
function openLockTokenCollateralGenerateDebtAndProtectSAFE(
address manager,
address taxCollector,
address collateralJoin,
address coinJoin,
bytes32 collateralType,
uint collateralAmount,
uint deltaWad,
bool transferFrom,
address liquidationEngine,
address saviour
) public returns (uint safe) {
safe = openSAFE(manager, collateralType, address(this));
lockTokenCollateralAndGenerateDebt(manager, taxCollector, collateralJoin, coinJoin, safe, collateralAmount, deltaWad, transferFrom);
protectSAFE(manager, safe, liquidationEngine, saviour);
}
function openLockGNTAndGenerateDebt(
address manager,
address taxCollector,
address gntJoin,
address coinJoin,
bytes32 collateralType,
uint collateralAmount,
uint deltaWad
) public returns (address bag, uint safe) {
// Creates bag (if doesn't exist) to hold GNT
bag = GNTJoinLike(gntJoin).bags(address(this));
if (bag == address(0)) {
bag = makeCollateralBag(gntJoin);
}
// Transfer funds to the funds which previously were sent to the proxy
CollateralLike_3(CollateralJoinLike_2(gntJoin).collateral()).transfer(bag, collateralAmount);
safe = openLockTokenCollateralAndGenerateDebt(manager, taxCollector, gntJoin, coinJoin, collateralType, collateralAmount, deltaWad, false);
}
function openLockGNTGenerateDebtAndProtectSAFE(
address manager,
address taxCollector,
address gntJoin,
address coinJoin,
bytes32 collateralType,
uint collateralAmount,
uint deltaWad,
address liquidationEngine,
address saviour
) public returns (address bag, uint safe) {
(bag, safe) = openLockGNTAndGenerateDebt(
manager,
taxCollector,
gntJoin,
coinJoin,
collateralType,
collateralAmount,
deltaWad
);
protectSAFE(manager, safe, liquidationEngine, saviour);
}
function repayAllDebtAndFreeETH(
address manager,
address ethJoin,
address coinJoin,
uint safe,
uint collateralWad
) public {
address safeEngine = ManagerLike(manager).safeEngine();
address safeHandler = ManagerLike(manager).safes(safe);
bytes32 collateralType = ManagerLike(manager).collateralTypes(safe);
(, uint generatedDebt) = SAFEEngineLike_15(safeEngine).safes(collateralType, safeHandler);
// Joins COIN amount into the safeEngine
coinJoin_join(coinJoin, safeHandler, _getRepaidAlDebt(safeEngine, safeHandler, safeHandler, collateralType));
// Paybacks debt to the SAFE and unlocks WETH amount from it
modifySAFECollateralization(
manager,
safe,
-toInt(collateralWad),
-int(generatedDebt)
);
// Moves the amount from the SAFE handler to proxy's address
transferCollateral(manager, safe, address(this), collateralWad);
// Exits WETH amount to proxy address as a token
CollateralJoinLike_2(ethJoin).exit(address(this), collateralWad);
// Converts WETH to ETH
CollateralJoinLike_2(ethJoin).collateral().withdraw(collateralWad);
// Sends ETH back to the user's wallet
msg.sender.transfer(collateralWad);
}
function repayDebtAndFreeTokenCollateral(
address manager,
address collateralJoin,
address coinJoin,
uint safe,
uint collateralAmount,
uint deltaWad
) external {
address safeHandler = ManagerLike(manager).safes(safe);
// Joins COIN amount into the safeEngine
coinJoin_join(coinJoin, safeHandler, deltaWad);
uint collateralWad = convertTo18(collateralJoin, collateralAmount);
// Paybacks debt to the SAFE and unlocks token amount from it
modifySAFECollateralization(
manager,
safe,
-toInt(collateralWad),
_getRepaidDeltaDebt(ManagerLike(manager).safeEngine(), SAFEEngineLike_15(ManagerLike(manager).safeEngine()).coinBalance(safeHandler), safeHandler, ManagerLike(manager).collateralTypes(safe))
);
// Moves the amount from the SAFE handler to proxy's address
transferCollateral(manager, safe, address(this), collateralWad);
// Exits token amount to the user's wallet as a token
CollateralJoinLike_2(collateralJoin).exit(msg.sender, collateralAmount);
}
function repayAllDebtAndFreeTokenCollateral(
address manager,
address collateralJoin,
address coinJoin,
uint safe,
uint collateralAmount
) public {
address safeEngine = ManagerLike(manager).safeEngine();
address safeHandler = ManagerLike(manager).safes(safe);
bytes32 collateralType = ManagerLike(manager).collateralTypes(safe);
(, uint generatedDebt) = SAFEEngineLike_15(safeEngine).safes(collateralType, safeHandler);
// Joins COIN amount into the safeEngine
coinJoin_join(coinJoin, safeHandler, _getRepaidAlDebt(safeEngine, safeHandler, safeHandler, collateralType));
uint collateralWad = convertTo18(collateralJoin, collateralAmount);
// Paybacks debt to the SAFE and unlocks token amount from it
modifySAFECollateralization(
manager,
safe,
-toInt(collateralWad),
-int(generatedDebt)
);
// Moves the amount from the SAFE handler to proxy's address
transferCollateral(manager, safe, address(this), collateralWad);
// Exits token amount to the user's wallet as a token
CollateralJoinLike_2(collateralJoin).exit(msg.sender, collateralAmount);
}
}
contract GebProxyActionsGlobalSettlement is Common {
// Internal functions
function _freeCollateral(
address manager,
address globalSettlement,
uint safe
) internal returns (uint lockedCollateral) {
bytes32 collateralType = ManagerLike(manager).collateralTypes(safe);
address safeHandler = ManagerLike(manager).safes(safe);
SAFEEngineLike_15 safeEngine = SAFEEngineLike_15(ManagerLike(manager).safeEngine());
uint generatedDebt;
(lockedCollateral, generatedDebt) = safeEngine.safes(collateralType, safeHandler);
// If SAFE still has debt, it needs to be paid
if (generatedDebt > 0) {
GlobalSettlementLike_3(globalSettlement).processSAFE(collateralType, safeHandler);
(lockedCollateral,) = safeEngine.safes(collateralType, safeHandler);
}
// Approves the manager to transfer the position to proxy's address in the safeEngine
if (safeEngine.canModifySAFE(address(this), address(manager)) == 0) {
safeEngine.approveSAFEModification(manager);
}
// Transfers position from SAFE to the proxy address
ManagerLike(manager).quitSystem(safe, address(this));
// Frees the position and recovers the collateral in the safeEngine registry
GlobalSettlementLike_3(globalSettlement).freeCollateral(collateralType);
}
// Public functions
function freeETH(
address manager,
address ethJoin,
address globalSettlement,
uint safe
) external {
uint wad = _freeCollateral(manager, globalSettlement, safe);
// Exits WETH amount to proxy address as a token
CollateralJoinLike_2(ethJoin).exit(address(this), wad);
// Converts WETH to ETH
CollateralJoinLike_2(ethJoin).collateral().withdraw(wad);
// Sends ETH back to the user's wallet
msg.sender.transfer(wad);
}
function freeTokenCollateral(
address manager,
address collateralJoin,
address globalSettlement,
uint safe
) public {
uint amt = _freeCollateral(manager, globalSettlement, safe) / 10 ** (18 - CollateralJoinLike_2(collateralJoin).decimals());
// Exits token amount to the user's wallet as a token
CollateralJoinLike_2(collateralJoin).exit(msg.sender, amt);
}
function prepareCoinsForRedeeming(
address coinJoin,
address globalSettlement,
uint wad
) public {
coinJoin_join(coinJoin, address(this), wad);
SAFEEngineLike_15 safeEngine = CoinJoinLike_3(coinJoin).safeEngine();
// Approves the globalSettlement to take out COIN from the proxy's balance in the safeEngine
if (safeEngine.canModifySAFE(address(this), address(globalSettlement)) == 0) {
safeEngine.approveSAFEModification(globalSettlement);
}
GlobalSettlementLike_3(globalSettlement).prepareCoinsForRedeeming(wad);
}
function redeemETH(
address ethJoin,
address globalSettlement,
bytes32 collateralType,
uint wad
) public {
GlobalSettlementLike_3(globalSettlement).redeemCollateral(collateralType, wad);
uint collateralWad = multiply(wad, GlobalSettlementLike_3(globalSettlement).collateralCashPrice(collateralType)) / RAY;
// Exits WETH amount to proxy address as a token
CollateralJoinLike_2(ethJoin).exit(address(this), collateralWad);
// Converts WETH to ETH
CollateralJoinLike_2(ethJoin).collateral().withdraw(collateralWad);
// Sends ETH back to the user's wallet
msg.sender.transfer(collateralWad);
}
function redeemTokenCollateral(
address collateralJoin,
address globalSettlement,
bytes32 collateralType,
uint wad
) public {
GlobalSettlementLike_3(globalSettlement).redeemCollateral(collateralType, wad);
// Exits token amount to the user's wallet as a token
uint amt = multiply(wad, GlobalSettlementLike_3(globalSettlement).collateralCashPrice(collateralType)) / RAY / 10 ** (18 - CollateralJoinLike_2(collateralJoin).decimals());
CollateralJoinLike_2(collateralJoin).exit(msg.sender, amt);
}
}
contract GebProxyActionsCoinSavingsAccount is Common {
function deposit(
address coinJoin,
address coinSavingsAccount,
uint wad
) public {
SAFEEngineLike_15 safeEngine = CoinJoinLike_3(coinJoin).safeEngine();
// Executes updateAccumulatedRate to get the accumulatedRates updated to latestUpdateTime == now, otherwise join will fail
uint accumulatedRates = CoinSavingsAccountLike_2(coinSavingsAccount).updateAccumulatedRate();
// Joins wad amount to the safeEngine balance
coinJoin_join(coinJoin, address(this), wad);
// Approves the coinSavingsAccount to take out COIN from the proxy's balance in the safeEngine
if (safeEngine.canModifySAFE(address(this), address(coinSavingsAccount)) == 0) {
safeEngine.approveSAFEModification(coinSavingsAccount);
}
// Joins the savings value (equivalent to the COIN wad amount) in the coinSavingsAccount
CoinSavingsAccountLike_2(coinSavingsAccount).deposit(multiply(wad, RAY) / accumulatedRates);
}
function withdraw(
address coinJoin,
address coinSavingsAccount,
uint wad
) public {
SAFEEngineLike_15 safeEngine = CoinJoinLike_3(coinJoin).safeEngine();
// Executes updateAccumulatedRate to count the savings accumulated until this moment
uint accumulatedRates = CoinSavingsAccountLike_2(coinSavingsAccount).updateAccumulatedRate();
// Calculates the savings value in the coinSavingsAccount equivalent to the COIN wad amount
uint savings = multiply(wad, RAY) / accumulatedRates;
// Exits COIN from the coinSavingsAccount
CoinSavingsAccountLike_2(coinSavingsAccount).withdraw(savings);
// Checks the actual balance of COIN in the safeEngine after the coinSavingsAccount exit
uint bal = CoinJoinLike_3(coinJoin).safeEngine().coinBalance(address(this));
// Allows adapter to access to proxy's COIN balance in the safeEngine
if (safeEngine.canModifySAFE(address(this), address(coinJoin)) == 0) {
safeEngine.approveSAFEModification(coinJoin);
}
// It is necessary to check if due rounding the exact wad amount can be exited by the adapter.
// Otherwise it will do the minimum COIN balance in the safeEngine
CoinJoinLike_3(coinJoin).exit(
msg.sender,
bal >= multiply(wad, RAY) ? wad : bal / RAY
);
}
function withdrawAll(
address coinJoin,
address coinSavingsAccount
) public {
SAFEEngineLike_15 safeEngine = CoinJoinLike_3(coinJoin).safeEngine();
// Executes updateAccumulatedRate to count the savings accumulated until this moment
uint accumulatedRates = CoinSavingsAccountLike_2(coinSavingsAccount).updateAccumulatedRate();
// Gets the total savings belonging to the proxy address
uint savings = CoinSavingsAccountLike_2(coinSavingsAccount).savings(address(this));
// Exits COIN from the coinSavingsAccount
CoinSavingsAccountLike_2(coinSavingsAccount).withdraw(savings);
// Allows adapter to access to proxy's COIN balance in the safeEngine
if (safeEngine.canModifySAFE(address(this), address(coinJoin)) == 0) {
safeEngine.approveSAFEModification(coinJoin);
}
// Exits the COIN amount corresponding to the value of savings
CoinJoinLike_3(coinJoin).exit(msg.sender, multiply(accumulatedRates, savings) / RAY);
}
}
////// src/GebProxySaviourActions.sol
/// GebProxySaviourActions.sol
// Copyright (C) 2018-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.7; */
/* import "./GebProxyActions.sol"; */
abstract contract GebSaviourLike {
function deposit(uint256, uint256) virtual external;
function deposit(bytes32, uint256, uint256) virtual external;
function withdraw(uint256, uint256, address) virtual external;
function withdraw(bytes32, uint256, uint256, address) virtual external;
function getReserves(uint256, address) virtual external;
}
abstract contract SaviourCRatioSetterLike_2 {
function setDesiredCollateralizationRatio(bytes32, uint256, uint256) virtual external;
}
/// @title Saviour proxy actions
/// @notice This contract is supposed to be used alongside a DSProxy contract
/// @dev These functions are meant to be used as a a library for a DSProxy
contract GebProxySaviourActions {
// --- Internal Logic ---
/*
* @notice Transfer a token from the caller to the proxy and approve another address to pull the tokens from the proxy
* @param token The token being transferred and approved
* @param target The address that can pull tokens from the proxy
* @param amount The amount of tokens being transferred and approved
*/
function transferTokenFromAndApprove(address token, address target, uint256 amount) internal {
DSTokenLike_3(token).transferFrom(msg.sender, address(this), amount);
DSTokenLike_3(token).approve(target, 0);
DSTokenLike_3(token).approve(target, amount);
}
// --- External Logic ---
/*
* @notice Transfer all tokens that the proxy has out of an array of tokens to the caller
* @param tokens The array of tokens being transfered
*/
function transferTokensToCaller(address[] memory tokens) public {
for (uint i = 0; i < tokens.length; i++) {
uint256 selfBalance = DSTokenLike_3(tokens[i]).balanceOf(address(this));
if (selfBalance > 0) {
DSTokenLike_3(tokens[i]).transfer(msg.sender, selfBalance);
}
}
}
/*
* @notice Attach a saviour to a SAFE
* @param saviour The saviour contract being attached
* @param manager The SAFE manager contract
* @param safe The ID of the SAFE being covered
* @param liquidationEngine The LiquidationEngine contract
*/
function protectSAFE(
address saviour,
address manager,
uint safe,
address liquidationEngine
) public {
ManagerLike(manager).protectSAFE(safe, liquidationEngine, saviour);
}
/*
* @notice Set a custom desired collateralization ratio for a specific SAFE
* @param cRatioSetter The address of the saviour cRatio setter
* @param collateralType The collateral type of the SAFE
* @param safe The ID of the SAFE
* @param cRatio The desired collateralization ratio for the SAFE
*/
function setDesiredCollateralizationRatio(
address cRatioSetter,
bytes32 collateralType,
uint256 safe,
uint256 cRatio
) public {
SaviourCRatioSetterLike_2(cRatioSetter).setDesiredCollateralizationRatio(collateralType, safe, cRatio);
}
/*
* @notice Deposit cover in a saviour contract
* @param collateralSpecific Whether the collateral type of the SAFE needs to be passed to the saviour contract
* @param saviour The saviour contract being attached
* @param manager The SAFE manager contract
* @param token The token being used as cover
* @param safe The ID of the SAFE being covered
* @param tokenAmount The amount of tokens being deposited as cover
*/
function deposit(
bool collateralSpecific,
address saviour,
address manager,
address token,
uint256 safe,
uint256 tokenAmount
) public {
transferTokenFromAndApprove(token, saviour, tokenAmount);
if (collateralSpecific) {
GebSaviourLike(saviour).deposit(ManagerLike(manager).collateralTypes(safe), safe, tokenAmount);
} else {
GebSaviourLike(saviour).deposit(safe, tokenAmount);
}
}
/*
* @notice Set a custom desired collateralization ratio for a specific SAFE and deposit cover in a saviour for the SAFE
* @param collateralSpecific Whether the collateral type of the SAFE needs to be passed to the saviour contract
* @param saviour The saviour contract being attached
* @param cRatioSetter The address of the saviour cRatio setter
* @param manager The SAFE manager contract
* @param token The token being used as cover
* @param safe The ID of the SAFE being covered
* @param tokenAmount The amount of tokens being deposited as cover
* @param cRatio The desired collateralization ratio for the SAFE
*/
function setDesiredCRatioDeposit(
bool collateralSpecific,
address saviour,
address cRatioSetter,
address manager,
address token,
uint256 safe,
uint256 tokenAmount,
uint256 cRatio
) public {
setDesiredCollateralizationRatio(cRatioSetter, ManagerLike(manager).collateralTypes(safe), safe, cRatio);
deposit(collateralSpecific, saviour, manager, token, safe, tokenAmount);
}
/*
* @notice Withdraw cover from a saviour contract
* @param collateralSpecific Whether the collateral type of the SAFE needs to be passed to the saviour contract
* @param saviour The saviour contract from which to withdraw cover
* @param manager The SAFE manager contract
* @param safe The ID of the SAFE being covered
* @param tokenAmount The amount of tokens being withdrawn
* @param dst The address that will receive the withdrawn tokens
*/
function withdraw(
bool collateralSpecific,
address saviour,
address manager,
uint256 safe,
uint256 tokenAmount,
address dst
) public {
if (collateralSpecific) {
GebSaviourLike(saviour).withdraw(ManagerLike(manager).collateralTypes(safe), safe, tokenAmount, dst);
} else {
GebSaviourLike(saviour).withdraw(safe, tokenAmount, dst);
}
}
/*
* @notice Set a custom desired collateralization ratio for a specific SAFE and withdraw cover from a saviour protecting the SAFE
* @param collateralSpecific Whether the collateral type of the SAFE needs to be passed to the saviour contract
* @param saviour The saviour contract from which to withdraw cover
* @param cRatioSetter The address of the saviour cRatio setter
* @param manager The SAFE manager contract
* @param safe The ID of the SAFE being covered
* @param tokenAmount The amount of tokens being withdrawn
* @param cRatio The desired collateralization ratio for the SAFE
* @param dst The address that will receive the withdrawn tokens
*/
function setDesiredCRatioWithdraw(
bool collateralSpecific,
address saviour,
address cRatioSetter,
address manager,
uint256 safe,
uint256 tokenAmount,
uint256 cRatio,
address dst
) public {
setDesiredCollateralizationRatio(cRatioSetter, ManagerLike(manager).collateralTypes(safe), safe, cRatio);
withdraw(collateralSpecific, saviour, manager, safe, tokenAmount, dst);
}
/*
* @notice Attach a saviour to a SAFE and deposit cover in it
* @param collateralSpecific Whether the collateral type of the SAFE needs to be passed to the saviour contract
* @param saviour The saviour contract being attached
* @param manager The SAFE manager contract
* @param token The token being used as cover
* @param liquidationEngine The LiquidationEngine contract
* @param safe The ID of the SAFE being covered
* @param tokenAmount The amount of tokens being deposited as cover
*/
function protectSAFEDeposit(
bool collateralSpecific,
address saviour,
address manager,
address token,
address liquidationEngine,
uint256 safe,
uint256 tokenAmount
) public {
protectSAFE(saviour, manager, safe, liquidationEngine);
deposit(collateralSpecific, saviour, manager, token, safe, tokenAmount);
}
/*
* @notice Attach a saviour to a SAFE, set the SAFE's desired cRatio and deposit cover in the saviour
* @param collateralSpecific Whether the collateral type of the SAFE needs to be passed to the saviour contract
* @param saviour The saviour contract being attached
* @param cRatioSetter The cRatio setter contract
* @param manager The SAFE manager contract
* @param token The token being used as cover
* @param liquidationEngine The LiquidationEngine contract
* @param safe The ID of the SAFE being covered
* @param tokenAmount The amount of tokens being deposited as cover
* @param cRatio The desired collateralization ratio
*/
function protectSAFESetDesiredCRatioDeposit(
bool collateralSpecific,
address saviour,
address cRatioSetter,
address manager,
address token,
address liquidationEngine,
uint256 safe,
uint256 tokenAmount,
uint256 cRatio
) public {
protectSAFE(saviour, manager, safe, liquidationEngine);
setDesiredCollateralizationRatio(cRatioSetter, ManagerLike(manager).collateralTypes(safe), safe, cRatio);
deposit(collateralSpecific, saviour, manager, token, safe, tokenAmount);
}
/*
* @notice Withdraw cover from a saviour and uncover a SAFE
* @param collateralSpecific Whether the collateral type of the SAFE needs to be passed to the saviour contract
* @param saviour The saviour contract being detached
* @param manager The SAFE manager contract
* @param token The token being used as cover
* @param liquidationEngine The LiquidationEngine contract
* @param safe The ID of the SAFE being covered
* @param tokenAmount The amount of tokens being withdrawn
* @param dst The address that will receive the withdrawn tokens
*/
function withdrawUncoverSAFE(
bool collateralSpecific,
address saviour,
address manager,
address token,
address liquidationEngine,
uint256 safe,
uint256 tokenAmount,
address dst
) public {
withdraw(collateralSpecific, saviour, manager, safe, tokenAmount, dst);
protectSAFE(address(0), manager, safe, liquidationEngine);
}
/*
* @notice Withdraw cover from a saviour, cover a SAFE with a new saviour and deposit cover in the new saviour
* @param withdrawCollateralSpecific Whether the collateral type of the SAFE needs to be passed to the withdraw saviour contract
* @param depositCollateralSpecific Whether the collateral type of the SAFE needs to be passed to the deposit saviour contract
* @param withdrawSaviour The saviour from which cover is being withdrawn
* @param depositSaviour The new saviour that wil protect the SAFE
* @param manager The SAFE manager contract
* @param depositToken The token being deposited in the depositSaviour
* @param liquidationEngine The LiquidationEngine contract
* @param safe The SAFE being covered by the new saviour
* @param withdrawTokenAmount The amount of tokens being withdrawn from the old saviour
* @param depositTokenAmount The amount of tokens being deposited in the new saviour
* @param withdrawDst The address that will receive the withdrawn tokens
*/
function withdrawProtectSAFEDeposit(
bool withdrawCollateralSpecific,
bool depositCollateralSpecific,
address withdrawSaviour,
address depositSaviour,
address manager,
address depositToken,
address liquidationEngine,
uint256 safe,
uint256 withdrawTokenAmount,
uint256 depositTokenAmount,
address withdrawDst
) public {
withdraw(withdrawCollateralSpecific, withdrawSaviour, manager, safe, withdrawTokenAmount, withdrawDst);
protectSAFE(depositSaviour, manager, safe, liquidationEngine);
deposit(depositCollateralSpecific, depositSaviour, manager, depositToken, safe, depositTokenAmount);
}
/*
* @notice Withdraw reserve tokens from a saviour without uncovering a SAFE
* @param saviour The saviour from which to withdraw reserve assets
* @param safe The ID of the SAFE that has tokens in reserves
* @param The address that will receive the reserve tokens
*/
function getReserves(address saviour, uint256 safe, address dst) public {
GebSaviourLike(saviour).getReserves(safe, dst);
}
/*
* @notice Withdraw reserve tokens from a saviour and uncover a SAFE
* @param saviour The saviour from which to withdraw reserve assets
* @param manager The SAFE manager contract
* @param liquidationEngine The LiquidationEngine contract
* @param safe The ID of the SAFE that has tokens in reserves
* @param The address that will receive the reserve tokens
*/
function getReservesAndUncover(address saviour, address manager, address liquidationEngine, uint256 safe, address dst) public {
GebSaviourLike(saviour).getReserves(safe, dst);
protectSAFE(address(0), manager, safe, liquidationEngine);
}
}
| Exits the COIN amount corresponding to the value of savings | CoinJoinLike_3(coinJoin).exit(msg.sender, multiply(accumulatedRates, savings) / RAY);
| 13,562,919 | [
1,
424,
1282,
326,
385,
6266,
3844,
4656,
358,
326,
460,
434,
4087,
899,
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,
28932,
4572,
8804,
67,
23,
12,
12645,
4572,
2934,
8593,
12,
3576,
18,
15330,
16,
10194,
12,
8981,
5283,
690,
20836,
16,
4087,
899,
13,
342,
534,
5255,
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
]
|
//Address: 0xeaa76f1f32ced565c78bf1d57546002a0b0d9684
//Contract name: Crowdsale
//Balance: 0 Ether
//Verification Date: 3/26/2018
//Transacion Count: 41
// CODE STARTS HERE
pragma solidity 0.4.21;
library SafeMath {
function mul(uint a, uint b) internal pure returns(uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function sub(uint a, uint b) internal pure returns(uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
newOwner = address(0);
}
/**
* @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(address(0) != _newOwner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, msg.sender);
owner = msg.sender;
newOwner = address(0);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
// Crowdsale Smart Contract
// This smart contract collects ETH and in return sends tokens to contributors
contract Crowdsale is Pausable {
using SafeMath for uint;
struct Backer {
uint weiReceived; // amount of ETH contributed
uint tokensToSend; // amount of tokens sent
bool refunded;
}
Token public token; // Token contract reference
address public multisig; // Multisig contract that will receive the ETH
address public team; // Address at which the team tokens will be sent
uint public ethReceivedPresale; // Number of ETH received in presale
uint public ethReceivedMain; // Number of ETH received in public sale
uint public tokensSentPresale; // Tokens sent during presale
uint public tokensSentMain; // Tokens sent during public ICO
uint public totalTokensSent; // Total number of tokens sent to contributors
uint public startBlock; // Crowdsale start block
uint public endBlock; // Crowdsale end block
uint public maxCap; // Maximum number of tokens to sell
uint public minInvestETH; // Minimum amount to invest
bool public crowdsaleClosed; // Is crowdsale still in progress
Step public currentStep; // To allow for controlled steps of the campaign
uint public refundCount; // Number of refunds
uint public totalRefunded; // Total amount of Eth refunded
uint public numOfBlocksInMinute; // number of blocks in one minute * 100. eg.
WhiteList public whiteList; // whitelist contract
uint public tokenPriceWei; // Price of token in wei
mapping(address => Backer) public backers; // contributors list
address[] public backersIndex; // to be able to iterate through backers for verification.
uint public priorTokensSent;
uint public presaleCap;
// @notice to verify if action is not performed out of the campaign range
modifier respectTimeFrame() {
require(block.number >= startBlock && block.number <= endBlock);
_;
}
// @notice to set and determine steps of crowdsale
enum Step {
FundingPreSale, // presale mode
FundingPublicSale, // public mode
Refunding // in case campaign failed during this step contributors will be able to receive refunds
}
// Events
event ReceivedETH(address indexed backer, uint amount, uint tokenAmount);
event RefundETH(address indexed backer, uint amount);
// Crowdsale {constructor}
// @notice fired when contract is crated. Initializes all constant and initial values.
// @param _dollarToEtherRatio {uint} how many dollars are in one eth. $333.44/ETH would be passed as 33344
function Crowdsale(WhiteList _whiteList) public {
require(_whiteList != address(0));
multisig = 0x10f78f2a70B52e6c3b490113c72Ba9A90ff1b5CA;
team = 0x10f78f2a70B52e6c3b490113c72Ba9A90ff1b5CA;
maxCap = 1510000000e8;
minInvestETH = 1 ether/2;
currentStep = Step.FundingPreSale;
numOfBlocksInMinute = 408; // E.g. 4.38 block/per minute wold be entered as 438
priorTokensSent = 4365098999e7; //tokens distributed in private sale and airdrops
whiteList = _whiteList; // white list address
presaleCap = 160000000e8; // max for sell in presale
tokenPriceWei = 57142857142857; // 17500 tokens per ether
}
// @notice Specify address of token contract
// @param _tokenAddress {address} address of token contract
// @return res {bool}
function setTokenAddress(Token _tokenAddress) external onlyOwner() returns(bool res) {
require(token == address(0));
token = _tokenAddress;
return true;
}
// @notice set the step of the campaign from presale to public sale
// contract is deployed in presale mode
// WARNING: there is no way to go back
function advanceStep() public onlyOwner() {
require(Step.FundingPreSale == currentStep);
currentStep = Step.FundingPublicSale;
minInvestETH = 1 ether/4;
}
// @notice in case refunds are needed, money can be returned to the contract
// and contract switched to mode refunding
function prepareRefund() public payable onlyOwner() {
require(crowdsaleClosed);
require(msg.value == ethReceivedPresale.add(ethReceivedMain)); // make sure that proper amount of ether is sent
currentStep = Step.Refunding;
}
// @notice return number of contributors
// @return {uint} number of contributors
function numberOfBackers() public view returns(uint) {
return backersIndex.length;
}
// {fallback function}
// @notice It will call internal function which handles allocation of Ether and calculates tokens.
// Contributor will be instructed to specify sufficient amount of gas. e.g. 250,000
function () external payable {
contribute(msg.sender);
}
// @notice It will be called by owner to start the sale
function start(uint _block) external onlyOwner() {
require(startBlock == 0);
require(_block <= (numOfBlocksInMinute * 60 * 24 * 54)/100); // allow max 54 days for campaign
startBlock = block.number;
endBlock = startBlock.add(_block);
}
// @notice Due to changing average of block time
// this function will allow on adjusting duration of campaign closer to the end
function adjustDuration(uint _block) external onlyOwner() {
require(startBlock > 0);
require(_block < (numOfBlocksInMinute * 60 * 24 * 60)/100); // allow for max of 60 days for campaign
require(_block > block.number.sub(startBlock)); // ensure that endBlock is not set in the past
endBlock = startBlock.add(_block);
}
// @notice It will be called by fallback function whenever ether is sent to it
// @param _backer {address} address of contributor
// @return res {bool} true if transaction was successful
function contribute(address _backer) internal whenNotPaused() respectTimeFrame() returns(bool res) {
require(!crowdsaleClosed);
require(whiteList.isWhiteListed(_backer)); // ensure that user is whitelisted
uint tokensToSend = determinePurchase();
Backer storage backer = backers[_backer];
if (backer.weiReceived == 0)
backersIndex.push(_backer);
backer.tokensToSend += tokensToSend; // save contributor's total tokens sent
backer.weiReceived = backer.weiReceived.add(msg.value); // save contributor's total ether contributed
if (Step.FundingPublicSale == currentStep) { // Update the total Ether received and tokens sent during public sale
ethReceivedMain = ethReceivedMain.add(msg.value);
tokensSentMain += tokensToSend;
}else { // Update the total Ether recived and tokens sent during presale
ethReceivedPresale = ethReceivedPresale.add(msg.value);
tokensSentPresale += tokensToSend;
}
totalTokensSent += tokensToSend; // update the total amount of tokens sent
multisig.transfer(address(this).balance); // transfer funds to multisignature wallet
require(token.transfer(_backer, tokensToSend)); // Transfer tokens
emit ReceivedETH(_backer, msg.value, tokensToSend); // Register event
return true;
}
// @notice determine if purchase is valid and return proper number of tokens
// @return tokensToSend {uint} proper number of tokens based on the timline
function determinePurchase() internal view returns (uint) {
require(msg.value >= minInvestETH); // ensure that min contributions amount is met
uint tokensToSend = msg.value.mul(1e8) / tokenPriceWei; //1e8 ensures that token gets 8 decimal values
if (Step.FundingPublicSale == currentStep) { // calculate price of token in public sale
require(totalTokensSent + tokensToSend + priorTokensSent <= maxCap); // Ensure that max cap hasn't been reached
}else {
tokensToSend += (tokensToSend * 50) / 100;
require(totalTokensSent + tokensToSend <= presaleCap); // Ensure that max cap hasn't been reached for presale
}
return tokensToSend;
}
// @notice This function will finalize the sale.
// It will only execute if predetermined sale time passed or all tokens are sold.
// it will fail if minimum cap is not reached
function finalize() external onlyOwner() {
require(!crowdsaleClosed);
// purchasing precise number of tokens might be impractical, thus subtract 1000
// tokens so finalization is possible near the end
require(block.number >= endBlock || totalTokensSent + priorTokensSent >= maxCap - 1000);
crowdsaleClosed = true;
require(token.transfer(team, token.balanceOf(this))); // transfer all remaining tokens to team address
token.unlock();
}
// @notice Fail-safe drain
function drain() external onlyOwner() {
multisig.transfer(address(this).balance);
}
// @notice Fail-safe token transfer
function tokenDrain() external onlyOwner() {
if (block.number > endBlock) {
require(token.transfer(multisig, token.balanceOf(this)));
}
}
// @notice it will allow contributors to get refund in case campaign failed
// @return {bool} true if successful
function refund() external whenNotPaused() returns (bool) {
require(currentStep == Step.Refunding);
Backer storage backer = backers[msg.sender];
require(backer.weiReceived > 0); // ensure that user has sent contribution
require(!backer.refunded); // ensure that user hasn't been refunded yet
backer.refunded = true; // save refund status to true
refundCount++;
totalRefunded = totalRefunded + backer.weiReceived;
require(token.transfer(msg.sender, backer.tokensToSend)); // return allocated tokens
msg.sender.transfer(backer.weiReceived); // send back the contribution
emit RefundETH(msg.sender, backer.weiReceived);
return true;
}
}
contract ERC20 {
uint public totalSupply;
function balanceOf(address who) public view returns(uint);
function allowance(address owner, address spender) public view returns(uint);
function transfer(address to, uint value) public returns(bool ok);
function transferFrom(address from, address to, uint value) public returns(bool ok);
function approve(address spender, uint value) public returns(bool ok);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
// The token
contract Token is ERC20, Ownable {
using SafeMath for uint;
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals; // How many decimals to show.
string public version = "v0.1";
uint public totalSupply;
bool public locked;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
address public crowdSaleAddress;
// Lock transfer for contributors during the ICO
modifier onlyUnlocked() {
if (msg.sender != crowdSaleAddress && msg.sender != owner && locked)
revert();
_;
}
modifier onlyAuthorized() {
if (msg.sender != owner && msg.sender != crowdSaleAddress)
revert();
_;
}
// @notice The Token contract
function Token(address _crowdsaleAddress) public {
require(_crowdsaleAddress != address(0));
locked = true; // Lock the transfer of tokens during the crowdsale
totalSupply = 2600000000e8;
name = "Kripton"; // Set the name for display purposes
symbol = "LPK"; // Set the symbol for display purposes
decimals = 8; // Amount of decimals
crowdSaleAddress = _crowdsaleAddress;
balances[_crowdsaleAddress] = totalSupply;
}
// @notice unlock token for trading
function unlock() public onlyAuthorized {
locked = false;
}
// @lock token from trading during ICO
function lock() public onlyAuthorized {
locked = true;
}
// @notice transfer tokens to given address
// @param _to {address} address or recipient
// @param _value {uint} amount to transfer
// @return {bool} true if successful
function transfer(address _to, uint _value) public onlyUnlocked returns(bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
// @notice transfer tokens from given address to another address
// @param _from {address} from whom tokens are transferred
// @param _to {address} to whom tokens are transferred
// @parm _value {uint} amount of tokens to transfer
// @return {bool} true if successful
function transferFrom(address _from, address _to, uint256 _value) public onlyUnlocked returns(bool success) {
require(balances[_from] >= _value); // Check if the sender has enough
require(_value <= allowed[_from][msg.sender]); // Check if allowed is greater or equal
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
// @notice to query balance of account
// @return _owner {address} address of user to query balance
function balanceOf(address _owner) public view returns(uint balance) {
return balances[_owner];
}
/**
* @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, uint _value) public returns(bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
// @notice to query of allowance of one user to the other
// @param _owner {address} of the owner of the account
// @param _spender {address} of the spender of the account
// @return remaining {uint} amount of remaining allowance
function allowance(address _owner, address _spender) public view returns(uint remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// Whitelist smart contract
// This smart contract keeps list of addresses to whitelist
contract WhiteList is Ownable {
mapping(address => bool) public whiteList;
uint public totalWhiteListed; //white listed users number
event LogWhiteListed(address indexed user, uint whiteListedNum);
event LogWhiteListedMultiple(uint whiteListedNum);
event LogRemoveWhiteListed(address indexed user);
// @notice it will return status of white listing
// @return true if user is white listed and false if is not
function isWhiteListed(address _user) external view returns (bool) {
return whiteList[_user];
}
// @notice it will remove whitelisted user
// @param _contributor {address} of user to unwhitelist
function removeFromWhiteList(address _user) external onlyOwner() {
require(whiteList[_user] == true);
whiteList[_user] = false;
totalWhiteListed--;
emit LogRemoveWhiteListed(_user);
}
// @notice it will white list one member
// @param _user {address} of user to whitelist
// @return true if successful
function addToWhiteList(address _user) external onlyOwner() {
if (whiteList[_user] != true) {
whiteList[_user] = true;
totalWhiteListed++;
emit LogWhiteListed(_user, totalWhiteListed);
}else
revert();
}
// @notice it will white list multiple members
// @param _user {address[]} of users to whitelist
// @return true if successful
function addToWhiteListMultiple(address[] _users) external onlyOwner() {
for (uint i = 0; i < _users.length; ++i) {
if (whiteList[_users[i]] != true) {
whiteList[_users[i]] = true;
totalWhiteListed++;
}
}
emit LogWhiteListedMultiple(totalWhiteListed);
}
}
| allow max 54 days for campaign
| require(_block <= (numOfBlocksInMinute * 60 * 24 * 54)/100); | 5,503,316 | [
1,
5965,
943,
22431,
4681,
364,
8965,
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,
2583,
24899,
2629,
1648,
261,
2107,
951,
6450,
382,
18329,
380,
4752,
380,
4248,
380,
22431,
13176,
6625,
1769,
282,
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.4.6;
// --------------------------
// R Split Contract
// --------------------------
contract RSPLT_F {
event StatEvent(string msg);
event StatEventI(string msg, uint val);
enum SettingStateValue {debug, locked}
struct partnerAccount {
uint credited; // total funds credited to this account
uint balance; // current balance = credited - amount withdrawn
uint pctx10; // percent allocation times ten
address addr; // payout addr of this acct
bool evenStart; // even split up to evenDistThresh
}
// -----------------------------
// data storage
// ----------------------------------------
address public owner; // deployer executor
mapping (uint => partnerAccount) partnerAccounts; // accounts by index
uint public numAccounts; // how many accounts exist
uint public holdoverBalance; // amount yet to be distributed
uint public totalFundsReceived; // amount received since begin of time
uint public totalFundsDistributed; // amount distributed since begin of time
uint public totalFundsWithdrawn; // amount withdrawn since begin of time
uint public evenDistThresh; // distribute evenly until this amount (total)
uint public withdrawGas = 35000; // gas for withdrawals
uint constant TENHUNDWEI = 1000; // need gt. 1000 wei to do payout
uint constant MAX_ACCOUNTS = 5; // max accounts this contract can handle
SettingStateValue public settingsState = SettingStateValue.debug;
// --------------------
// contract constructor
// --------------------
function RSPLT_F() {
owner = msg.sender;
}
// -----------------------------------
// lock
// lock the contract. after calling this you will not be able to modify accounts:
// -----------------------------------
function lock() {
if (msg.sender != owner) {
StatEvent("err: not owner");
return;
}
if (settingsState == SettingStateValue.locked) {
StatEvent("err: locked");
return;
}
settingsState = SettingStateValue.locked;
StatEvent("ok: contract locked");
}
// -----------------------------------
// reset
// reset all accounts
// -----------------------------------
function reset() {
if (msg.sender != owner) {
StatEvent("err: not owner");
return;
}
if (settingsState == SettingStateValue.locked) {
StatEvent("err: locked");
return;
}
numAccounts = 0;
holdoverBalance = 0;
totalFundsReceived = 0;
totalFundsDistributed = 0;
totalFundsWithdrawn = 0;
StatEvent("ok: all accts reset");
}
// -----------------------------------
// set even distribution threshold
// -----------------------------------
function setEvenDistThresh(uint256 _thresh) {
if (msg.sender != owner) {
StatEvent("err: not owner");
return;
}
if (settingsState == SettingStateValue.locked) {
StatEvent("err: locked");
return;
}
evenDistThresh = (_thresh / TENHUNDWEI) * TENHUNDWEI;
StatEventI("ok: threshold set", evenDistThresh);
}
// -----------------------------------
// set even distribution threshold
// -----------------------------------
function setWitdrawGas(uint256 _withdrawGas) {
if (msg.sender != owner) {
StatEvent("err: not owner");
return;
}
withdrawGas = _withdrawGas;
StatEventI("ok: withdraw gas set", withdrawGas);
}
// ---------------------------------------------------
// add a new account
// ---------------------------------------------------
function addAccount(address _addr, uint256 _pctx10, bool _evenStart) {
if (msg.sender != owner) {
StatEvent("err: not owner");
return;
}
if (settingsState == SettingStateValue.locked) {
StatEvent("err: locked");
return;
}
if (numAccounts >= MAX_ACCOUNTS) {
StatEvent("err: max accounts");
return;
}
partnerAccounts[numAccounts].addr = _addr;
partnerAccounts[numAccounts].pctx10 = _pctx10;
partnerAccounts[numAccounts].evenStart = _evenStart;
partnerAccounts[numAccounts].credited = 0;
partnerAccounts[numAccounts].balance = 0;
++numAccounts;
StatEvent("ok: acct added");
}
// ----------------------------
// get acct info
// ----------------------------
function getAccountInfo(address _addr) constant returns(uint _idx, uint _pctx10, bool _evenStart, uint _credited, uint _balance) {
for (uint i = 0; i < numAccounts; i++ ) {
address addr = partnerAccounts[i].addr;
if (addr == _addr) {
_idx = i;
_pctx10 = partnerAccounts[i].pctx10;
_evenStart = partnerAccounts[i].evenStart;
_credited = partnerAccounts[i].credited;
_balance = partnerAccounts[i].balance;
StatEvent("ok: found acct");
return;
}
}
StatEvent("err: acct not found");
}
// ----------------------------
// get total percentages x10
// ----------------------------
function getTotalPctx10() constant returns(uint _totalPctx10) {
_totalPctx10 = 0;
for (uint i = 0; i < numAccounts; i++ ) {
_totalPctx10 += partnerAccounts[i].pctx10;
}
StatEventI("ok: total pctx10", _totalPctx10);
}
// ----------------------------
// get no. accts that are set for even split
// ----------------------------
function getNumEvenSplits() constant returns(uint _numEvenSplits) {
_numEvenSplits = 0;
for (uint i = 0; i < numAccounts; i++ ) {
if (partnerAccounts[i].evenStart) {
++_numEvenSplits;
}
}
StatEventI("ok: even splits", _numEvenSplits);
}
// -------------------------------------------
// default payable function.
// call us with plenty of gas, or catastrophe will ensue
// note: you can call this fcn with amount of zero to force distribution
// -------------------------------------------
function () payable {
totalFundsReceived += msg.value;
holdoverBalance += msg.value;
StatEventI("ok: incoming", msg.value);
}
// ----------------------------
// distribute funds to all partners
// ----------------------------
function distribute() {
//only payout if we have more than 1000 wei
if (holdoverBalance < TENHUNDWEI) {
return;
}
//first pay accounts that are not constrained by even distribution
//each account gets their prescribed percentage of this holdover.
uint i;
uint pctx10;
uint acctDist;
uint maxAcctDist;
uint numEvenSplits = 0;
for (i = 0; i < numAccounts; i++ ) {
if (partnerAccounts[i].evenStart) {
++numEvenSplits;
} else {
pctx10 = partnerAccounts[i].pctx10;
acctDist = holdoverBalance * pctx10 / TENHUNDWEI;
//we also double check to ensure that the amount awarded cannot exceed the
//total amount due to this acct. note: this check is necessary, cuz here we
//might not distribute the full holdover amount during each pass.
maxAcctDist = totalFundsReceived * pctx10 / TENHUNDWEI;
if (partnerAccounts[i].credited >= maxAcctDist) {
acctDist = 0;
} else if (partnerAccounts[i].credited + acctDist > maxAcctDist) {
acctDist = maxAcctDist - partnerAccounts[i].credited;
}
partnerAccounts[i].credited += acctDist;
partnerAccounts[i].balance += acctDist;
totalFundsDistributed += acctDist;
holdoverBalance -= acctDist;
}
}
//now pay accounts that are constrained by even distribution. we split whatever is
//left of the holdover evenly.
uint distAmount = holdoverBalance;
if (totalFundsDistributed < evenDistThresh) {
for (i = 0; i < numAccounts; i++ ) {
if (partnerAccounts[i].evenStart) {
acctDist = distAmount / numEvenSplits;
//we also double check to ensure that the amount awarded cannot exceed the
//total amount due to this acct. note: this check is necessary, cuz here we
//might not distribute the full holdover amount during each pass.
uint fundLimit = totalFundsReceived;
if (fundLimit > evenDistThresh)
fundLimit = evenDistThresh;
maxAcctDist = fundLimit / numEvenSplits;
if (partnerAccounts[i].credited >= maxAcctDist) {
acctDist = 0;
} else if (partnerAccounts[i].credited + acctDist > maxAcctDist) {
acctDist = maxAcctDist - partnerAccounts[i].credited;
}
partnerAccounts[i].credited += acctDist;
partnerAccounts[i].balance += acctDist;
totalFundsDistributed += acctDist;
holdoverBalance -= acctDist;
}
}
}
//now, if there are any funds left (because of a remainder in the even split), then distribute them
//according to percentages. note that this must be done here, even if we haven't passed the even distribution
//threshold, to ensure that we don't get stuck with a remainder amount that cannot be distributed.
distAmount = holdoverBalance;
if (distAmount > 0) {
for (i = 0; i < numAccounts; i++ ) {
if (partnerAccounts[i].evenStart) {
pctx10 = partnerAccounts[i].pctx10;
acctDist = distAmount * pctx10 / TENHUNDWEI;
//we also double check to ensure that the amount awarded cannot exceed the
//total amount due to this acct. note: this check is necessary, cuz here we
//might not distribute the full holdover amount during each pass.
maxAcctDist = totalFundsReceived * pctx10 / TENHUNDWEI;
if (partnerAccounts[i].credited >= maxAcctDist) {
acctDist = 0;
} else if (partnerAccounts[i].credited + acctDist > maxAcctDist) {
acctDist = maxAcctDist - partnerAccounts[i].credited;
}
partnerAccounts[i].credited += acctDist;
partnerAccounts[i].balance += acctDist;
totalFundsDistributed += acctDist;
holdoverBalance -= acctDist;
}
}
}
StatEvent("ok: distributed funds");
}
// ----------------------------
// withdraw account balance
// ----------------------------
function withdraw() {
for (uint i = 0; i < numAccounts; i++ ) {
address addr = partnerAccounts[i].addr;
if (addr == msg.sender) {
uint amount = partnerAccounts[i].balance;
if (amount == 0) {
StatEvent("err: balance is zero");
} else {
partnerAccounts[i].balance = 0;
totalFundsWithdrawn += amount;
if (!msg.sender.call.gas(withdrawGas).value(amount)())
throw;
StatEventI("ok: rewards paid", amount);
}
}
}
}
// ----------------------------
// suicide
// ----------------------------
function hariKari() {
if (msg.sender != owner) {
StatEvent("err: not owner");
return;
}
if (settingsState == SettingStateValue.locked) {
StatEvent("err: locked");
return;
}
suicide(owner);
}
} | amount yet to be distributed
| uint public holdoverBalance; | 6,452,219 | [
1,
8949,
4671,
358,
506,
16859,
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,
1071,
6887,
1643,
13937,
31,
12900,
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.16;
pragma experimental ABIEncoderV2;
import "./math/SafeMath.sol";
import "./token/ERC20/ERC20Burnable.sol";
import "./ownership/Ownable.sol";
import "./utils/StringUtils.sol";
/**
* @title Premium Subscription Token
* @dev Inherit from it to add ability for your token to sell premium subscriptions
*/
contract PremiumSubscriptionToken is ERC20Burnable, Ownable, StringUtils {
using SafeMath for uint256;
struct PremiumSubscriptionDuration {
uint256 openingTime;
uint256 closingTime;
}
struct PremiumSubscriptionType {
uint256 premiumSubscriptionTypeId;
uint256 premiumSubscriptionPricePerDay;
// You can add your own parameters here
}
event AddPremiumSubscriptionTypeEvent(uint256 _premiumSubscriptionTypeId);
event EditPremiumSubscriptionTypeEvent(uint256 _premiumSubscriptionTypeId);
event DeletePremiumSubscriptionTypeEvent(uint256 _premiumSubscriptionTypeId);
// If we have a record here, then user with address has a subscription with PremiumSubscriptionDuration duration to certain PremiumSubscriptionType
// string key = user address + premiumSubscriptionTypeId
// Even if we deleted premium type, such approach will allow us to fulfill existing premium subscription until they will expire
mapping(string => PremiumSubscriptionDuration) private premiumSubscriptionDurations;
// Database of all available premium subscription types
mapping(uint256 => PremiumSubscriptionType) private premiumSubscriptionTypes;
/**
* @dev Add new premium subscription type
* @param _premiumSubscriptionTypeId Id of the new subscription type
* @param _premiumSubscriptionPricePerDay Price per day of the new subscription type
*/
function addPremiumSubscriptionType(uint256 _premiumSubscriptionTypeId, uint256 _premiumSubscriptionPricePerDay) external onlyOwner {
PremiumSubscriptionType memory premiumSubscriptionType = PremiumSubscriptionType(_premiumSubscriptionTypeId, _premiumSubscriptionPricePerDay);
premiumSubscriptionTypes[_premiumSubscriptionTypeId] = premiumSubscriptionType;
emit AddPremiumSubscriptionTypeEvent(_premiumSubscriptionTypeId);
}
/**
* @dev Add new premium subscription types in batch
* @param _premiumSubscriptionTypeIds Ids of the new subscription types
* @param _premiumSubscriptionPricesPerDay Prices per day of the new subscription types
*/
function batchAddPremiumSubscriptionTypes(uint256[] calldata _premiumSubscriptionTypeIds, uint256[] calldata _premiumSubscriptionPricesPerDay) external onlyOwner {
require(_premiumSubscriptionTypeIds.length == _premiumSubscriptionPricesPerDay.length);
for (uint i=0; i<_premiumSubscriptionTypeIds.length; i++) {
PremiumSubscriptionType memory premiumSubscriptionType = PremiumSubscriptionType(_premiumSubscriptionTypeIds[i], _premiumSubscriptionPricesPerDay[i]);
premiumSubscriptionTypes[_premiumSubscriptionTypeIds[i]] = premiumSubscriptionType;
emit AddPremiumSubscriptionTypeEvent(_premiumSubscriptionTypeIds[i]);
}
}
/**
* @dev Edit existing premium subscription type
* @param _premiumSubscriptionTypeId Id of the existing subscription type
* @param _premiumSubscriptionPricePerDay Price per day of the existing subscription type to change
*/
function editPremiumSubscriptionType(uint256 _premiumSubscriptionTypeId, uint256 _premiumSubscriptionPricePerDay) external onlyOwner {
PremiumSubscriptionType memory premiumSubscriptionType = PremiumSubscriptionType(_premiumSubscriptionTypeId, _premiumSubscriptionPricePerDay);
premiumSubscriptionTypes[_premiumSubscriptionTypeId] = premiumSubscriptionType;
emit EditPremiumSubscriptionTypeEvent(_premiumSubscriptionTypeId);
}
/**
* @dev Edit existing premium subscription types in batch
* @param _premiumSubscriptionTypeIds Ids of the existing subscription types
* @param _premiumSubscriptionPricesPerDay Prices per day of the existing subscription types to change
*/
function batchEditPremiumSubscriptionTypes(uint256[] calldata _premiumSubscriptionTypeIds, uint256[] calldata _premiumSubscriptionPricesPerDay) external onlyOwner {
require(_premiumSubscriptionTypeIds.length == _premiumSubscriptionPricesPerDay.length);
for (uint i=0; i<_premiumSubscriptionTypeIds.length; i++) {
PremiumSubscriptionType memory premiumSubscriptionType = PremiumSubscriptionType(_premiumSubscriptionTypeIds[i], _premiumSubscriptionPricesPerDay[i]);
premiumSubscriptionTypes[_premiumSubscriptionTypeIds[i]] = premiumSubscriptionType;
emit EditPremiumSubscriptionTypeEvent(_premiumSubscriptionTypeIds[i]);
}
}
/**
* @dev Delete existing premium subscription type
* @param _premiumSubscriptionTypeId Id of the existing subscription type
*/
function deletePremiumSubscriptionType(uint256 _premiumSubscriptionTypeId) external onlyOwner {
delete premiumSubscriptionTypes[_premiumSubscriptionTypeId];
emit DeletePremiumSubscriptionTypeEvent(_premiumSubscriptionTypeId);
}
/**
* @dev Delete existing premium subscription types in batch
* @param _premiumSubscriptionTypeIds Ids of the existing subscription types
*/
function batchDeletePremiumSubscriptionTypes(uint256[] calldata _premiumSubscriptionTypeIds) external onlyOwner {
for (uint i=0; i<_premiumSubscriptionTypeIds.length; i++) {
delete premiumSubscriptionTypes[_premiumSubscriptionTypeIds[i]];
emit DeletePremiumSubscriptionTypeEvent(_premiumSubscriptionTypeIds[i]);
}
}
/**
* @dev Get the price of existing premium subscription type
* @param _premiumSubscriptionTypeId Id of the existing subscription type
* @return Price of the existing subscription type
*/
function getPremiumSubscriptionPricePerDay(uint256 _premiumSubscriptionTypeId) public view returns (uint256) {
return premiumSubscriptionTypes[_premiumSubscriptionTypeId].premiumSubscriptionPricePerDay;
}
/**
* @dev Buy premium subscription type with selected Id for N amount of days
* @param _days Amount of days, when subscription will be active
* @param _premiumSubscriptionTypeId Id of the subscription type, which user wants to buy
*/
function buyPremiumSubscription(uint _days, uint256 _premiumSubscriptionTypeId) external {
// We should have such premium subscription type
require(premiumSubscriptionTypes[_premiumSubscriptionTypeId].premiumSubscriptionTypeId != 0);
// User should have sufficient amount of tokens
require(balanceOf(msg.sender) >= _days * premiumSubscriptionTypes[_premiumSubscriptionTypeId].premiumSubscriptionPricePerDay, "Error: insufficient funds");
// User should not have active subscription (to not overwrite it)
require(!checkPremiumSubscription(msg.sender, _premiumSubscriptionTypeId), "Error: premium subscription is still active");
// Burn user tokens
burn(_days * premiumSubscriptionTypes[_premiumSubscriptionTypeId].premiumSubscriptionPricePerDay);
// Grant subscription
PremiumSubscriptionDuration memory premiumSubscriptionDuration = PremiumSubscriptionDuration(now, now + (_days * 1 days));
string memory key = string(abi.encodePacked(msg.sender, uintToString(_premiumSubscriptionTypeId)));
premiumSubscriptionDurations[key] = premiumSubscriptionDuration;
}
/**
* @dev Grant premium subscription type with selected Id for N amount of days to certain user
* @param _user Wallet address of the user
* @param _days Amount of days, when subscription will be active
* @param _premiumSubscriptionTypeId Id of the subscription type, which admin wants to grant
*/
function grantPremiumSubscription(address _user, uint _days, uint256 _premiumSubscriptionTypeId) external onlyOwner {
// We should have such premium subscription type
require(premiumSubscriptionTypes[_premiumSubscriptionTypeId].premiumSubscriptionTypeId != 0);
// User should not have active subscription (to not overwrite it)
require(!checkPremiumSubscription(_user, _premiumSubscriptionTypeId), "Error: premium subscription is still active");
// Grant subscription
PremiumSubscriptionDuration memory premiumSubscriptionDuration = PremiumSubscriptionDuration(now, now + (_days * 1 days));
string memory key = string(abi.encodePacked(_user, uintToString(_premiumSubscriptionTypeId)));
premiumSubscriptionDurations[key] = premiumSubscriptionDuration;
}
/**
* @dev Check premium subscription
* @param _user Wallet address of the user
* @param _premiumSubscriptionTypeId Id of the existing subscription type
* @return true if user have active subscription or false if not
*/
function checkPremiumSubscription(address _user, uint256 _premiumSubscriptionTypeId) public view returns (bool) {
string memory key = string(abi.encodePacked(_user, uintToString(_premiumSubscriptionTypeId)));
return block.timestamp >= premiumSubscriptionDurations[key].openingTime && block.timestamp <= premiumSubscriptionDurations[key].closingTime;
}
}
| * @title Premium Subscription Token @dev Inherit from it to add ability for your token to sell premium subscriptions/ | contract PremiumSubscriptionToken is ERC20Burnable, Ownable, StringUtils {
using SafeMath for uint256;
struct PremiumSubscriptionDuration {
uint256 openingTime;
uint256 closingTime;
}
struct PremiumSubscriptionType {
uint256 premiumSubscriptionTypeId;
uint256 premiumSubscriptionPricePerDay;
}
event AddPremiumSubscriptionTypeEvent(uint256 _premiumSubscriptionTypeId);
event EditPremiumSubscriptionTypeEvent(uint256 _premiumSubscriptionTypeId);
event DeletePremiumSubscriptionTypeEvent(uint256 _premiumSubscriptionTypeId);
mapping(string => PremiumSubscriptionDuration) private premiumSubscriptionDurations;
mapping(uint256 => PremiumSubscriptionType) private premiumSubscriptionTypes;
function addPremiumSubscriptionType(uint256 _premiumSubscriptionTypeId, uint256 _premiumSubscriptionPricePerDay) external onlyOwner {
PremiumSubscriptionType memory premiumSubscriptionType = PremiumSubscriptionType(_premiumSubscriptionTypeId, _premiumSubscriptionPricePerDay);
premiumSubscriptionTypes[_premiumSubscriptionTypeId] = premiumSubscriptionType;
emit AddPremiumSubscriptionTypeEvent(_premiumSubscriptionTypeId);
}
function batchAddPremiumSubscriptionTypes(uint256[] calldata _premiumSubscriptionTypeIds, uint256[] calldata _premiumSubscriptionPricesPerDay) external onlyOwner {
require(_premiumSubscriptionTypeIds.length == _premiumSubscriptionPricesPerDay.length);
for (uint i=0; i<_premiumSubscriptionTypeIds.length; i++) {
PremiumSubscriptionType memory premiumSubscriptionType = PremiumSubscriptionType(_premiumSubscriptionTypeIds[i], _premiumSubscriptionPricesPerDay[i]);
premiumSubscriptionTypes[_premiumSubscriptionTypeIds[i]] = premiumSubscriptionType;
emit AddPremiumSubscriptionTypeEvent(_premiumSubscriptionTypeIds[i]);
}
}
function batchAddPremiumSubscriptionTypes(uint256[] calldata _premiumSubscriptionTypeIds, uint256[] calldata _premiumSubscriptionPricesPerDay) external onlyOwner {
require(_premiumSubscriptionTypeIds.length == _premiumSubscriptionPricesPerDay.length);
for (uint i=0; i<_premiumSubscriptionTypeIds.length; i++) {
PremiumSubscriptionType memory premiumSubscriptionType = PremiumSubscriptionType(_premiumSubscriptionTypeIds[i], _premiumSubscriptionPricesPerDay[i]);
premiumSubscriptionTypes[_premiumSubscriptionTypeIds[i]] = premiumSubscriptionType;
emit AddPremiumSubscriptionTypeEvent(_premiumSubscriptionTypeIds[i]);
}
}
function editPremiumSubscriptionType(uint256 _premiumSubscriptionTypeId, uint256 _premiumSubscriptionPricePerDay) external onlyOwner {
PremiumSubscriptionType memory premiumSubscriptionType = PremiumSubscriptionType(_premiumSubscriptionTypeId, _premiumSubscriptionPricePerDay);
premiumSubscriptionTypes[_premiumSubscriptionTypeId] = premiumSubscriptionType;
emit EditPremiumSubscriptionTypeEvent(_premiumSubscriptionTypeId);
}
function batchEditPremiumSubscriptionTypes(uint256[] calldata _premiumSubscriptionTypeIds, uint256[] calldata _premiumSubscriptionPricesPerDay) external onlyOwner {
require(_premiumSubscriptionTypeIds.length == _premiumSubscriptionPricesPerDay.length);
for (uint i=0; i<_premiumSubscriptionTypeIds.length; i++) {
PremiumSubscriptionType memory premiumSubscriptionType = PremiumSubscriptionType(_premiumSubscriptionTypeIds[i], _premiumSubscriptionPricesPerDay[i]);
premiumSubscriptionTypes[_premiumSubscriptionTypeIds[i]] = premiumSubscriptionType;
emit EditPremiumSubscriptionTypeEvent(_premiumSubscriptionTypeIds[i]);
}
}
function batchEditPremiumSubscriptionTypes(uint256[] calldata _premiumSubscriptionTypeIds, uint256[] calldata _premiumSubscriptionPricesPerDay) external onlyOwner {
require(_premiumSubscriptionTypeIds.length == _premiumSubscriptionPricesPerDay.length);
for (uint i=0; i<_premiumSubscriptionTypeIds.length; i++) {
PremiumSubscriptionType memory premiumSubscriptionType = PremiumSubscriptionType(_premiumSubscriptionTypeIds[i], _premiumSubscriptionPricesPerDay[i]);
premiumSubscriptionTypes[_premiumSubscriptionTypeIds[i]] = premiumSubscriptionType;
emit EditPremiumSubscriptionTypeEvent(_premiumSubscriptionTypeIds[i]);
}
}
function deletePremiumSubscriptionType(uint256 _premiumSubscriptionTypeId) external onlyOwner {
delete premiumSubscriptionTypes[_premiumSubscriptionTypeId];
emit DeletePremiumSubscriptionTypeEvent(_premiumSubscriptionTypeId);
}
function batchDeletePremiumSubscriptionTypes(uint256[] calldata _premiumSubscriptionTypeIds) external onlyOwner {
for (uint i=0; i<_premiumSubscriptionTypeIds.length; i++) {
delete premiumSubscriptionTypes[_premiumSubscriptionTypeIds[i]];
emit DeletePremiumSubscriptionTypeEvent(_premiumSubscriptionTypeIds[i]);
}
}
function batchDeletePremiumSubscriptionTypes(uint256[] calldata _premiumSubscriptionTypeIds) external onlyOwner {
for (uint i=0; i<_premiumSubscriptionTypeIds.length; i++) {
delete premiumSubscriptionTypes[_premiumSubscriptionTypeIds[i]];
emit DeletePremiumSubscriptionTypeEvent(_premiumSubscriptionTypeIds[i]);
}
}
function getPremiumSubscriptionPricePerDay(uint256 _premiumSubscriptionTypeId) public view returns (uint256) {
return premiumSubscriptionTypes[_premiumSubscriptionTypeId].premiumSubscriptionPricePerDay;
}
function buyPremiumSubscription(uint _days, uint256 _premiumSubscriptionTypeId) external {
require(premiumSubscriptionTypes[_premiumSubscriptionTypeId].premiumSubscriptionTypeId != 0);
require(balanceOf(msg.sender) >= _days * premiumSubscriptionTypes[_premiumSubscriptionTypeId].premiumSubscriptionPricePerDay, "Error: insufficient funds");
require(!checkPremiumSubscription(msg.sender, _premiumSubscriptionTypeId), "Error: premium subscription is still active");
burn(_days * premiumSubscriptionTypes[_premiumSubscriptionTypeId].premiumSubscriptionPricePerDay);
PremiumSubscriptionDuration memory premiumSubscriptionDuration = PremiumSubscriptionDuration(now, now + (_days * 1 days));
string memory key = string(abi.encodePacked(msg.sender, uintToString(_premiumSubscriptionTypeId)));
premiumSubscriptionDurations[key] = premiumSubscriptionDuration;
}
function grantPremiumSubscription(address _user, uint _days, uint256 _premiumSubscriptionTypeId) external onlyOwner {
require(premiumSubscriptionTypes[_premiumSubscriptionTypeId].premiumSubscriptionTypeId != 0);
require(!checkPremiumSubscription(_user, _premiumSubscriptionTypeId), "Error: premium subscription is still active");
PremiumSubscriptionDuration memory premiumSubscriptionDuration = PremiumSubscriptionDuration(now, now + (_days * 1 days));
string memory key = string(abi.encodePacked(_user, uintToString(_premiumSubscriptionTypeId)));
premiumSubscriptionDurations[key] = premiumSubscriptionDuration;
}
function checkPremiumSubscription(address _user, uint256 _premiumSubscriptionTypeId) public view returns (bool) {
string memory key = string(abi.encodePacked(_user, uintToString(_premiumSubscriptionTypeId)));
return block.timestamp >= premiumSubscriptionDurations[key].openingTime && block.timestamp <= premiumSubscriptionDurations[key].closingTime;
}
}
| 12,615,071 | [
1,
23890,
5077,
12132,
3155,
225,
25953,
628,
518,
358,
527,
7123,
364,
3433,
1147,
358,
357,
80,
23020,
5077,
11912,
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
]
| [
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,
16351,
453,
2764,
5077,
6663,
1345,
353,
4232,
39,
3462,
38,
321,
429,
16,
14223,
6914,
16,
5778,
288,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
1958,
453,
2764,
5077,
6663,
5326,
288,
203,
3639,
2254,
5034,
10890,
950,
31,
203,
3639,
2254,
5034,
7647,
950,
31,
203,
565,
289,
203,
203,
565,
1958,
453,
2764,
5077,
6663,
559,
288,
203,
3639,
2254,
5034,
23020,
5077,
6663,
11731,
31,
203,
3639,
2254,
5034,
23020,
5077,
6663,
5147,
2173,
4245,
31,
203,
565,
289,
203,
203,
565,
871,
1436,
23890,
5077,
6663,
559,
1133,
12,
11890,
5034,
389,
1484,
81,
5077,
6663,
11731,
1769,
203,
565,
871,
15328,
23890,
5077,
6663,
559,
1133,
12,
11890,
5034,
389,
1484,
81,
5077,
6663,
11731,
1769,
203,
565,
871,
2504,
23890,
5077,
6663,
559,
1133,
12,
11890,
5034,
389,
1484,
81,
5077,
6663,
11731,
1769,
203,
203,
203,
203,
565,
2874,
12,
1080,
516,
453,
2764,
5077,
6663,
5326,
13,
3238,
23020,
5077,
6663,
5326,
87,
31,
203,
565,
2874,
12,
11890,
5034,
516,
453,
2764,
5077,
6663,
559,
13,
3238,
23020,
5077,
6663,
2016,
31,
203,
565,
445,
527,
23890,
5077,
6663,
559,
12,
11890,
5034,
389,
1484,
81,
5077,
6663,
11731,
16,
2254,
5034,
389,
1484,
81,
5077,
6663,
5147,
2173,
4245,
13,
3903,
1338,
5541,
288,
203,
3639,
453,
2764,
5077,
6663,
559,
3778,
23020,
5077,
6663,
559,
273,
453,
2764,
5077,
6663,
559,
24899,
1484,
81,
5077,
6663,
11731,
16,
389,
1484,
81,
5077,
6663,
5147,
2173,
4245,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHUSDT is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == _fujiAdmin.getController() || msg.sender == owner(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0xdAC17F958D2ee523a2206206994597C13D831ec7); // USDT
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) public onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into account all balances across providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of DAI in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) public onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
interface IVault {
// Events
// Log Users Deposit
event Deposit(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users withdraw
event Withdraw(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users borrow
event Borrow(address indexed userAddrs, address indexed asset, uint256 amount);
// Log Users debt repay
event Payback(address indexed userAddrs, address indexed asset, uint256 amount);
// Log New active provider
event SetActiveProvider(address providerAddr);
// Log Switch providers
event Switch(
address vault,
address fromProviderAddrs,
address toProviderAddr,
uint256 debtamount,
uint256 collattamount
);
// Core Vault Functions
function deposit(uint256 _collateralAmount) external payable;
function withdraw(int256 _withdrawAmount) external;
function borrow(uint256 _borrowAmount) external;
function payback(int256 _repayAmount) external payable;
function executeSwitch(
address _newProvider,
uint256 _flashLoanDebt,
uint256 _fee
) external;
//Getter Functions
function activeProvider() external view returns (address);
function borrowBalance(address _provider) external view returns (uint256);
function depositBalance(address _provider) external view returns (uint256);
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
external
view
returns (uint256);
function getLiquidationBonusFor(uint256 _amount, bool _flash) external view returns (uint256);
function getProviders() external view returns (address[] memory);
function fujiERC1155() external view returns (address);
//Setter Functions
function setActiveProvider(address _provider) external;
function updateF1155Balances() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Pausable } from "@openzeppelin/contracts/utils/Pausable.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
contract VaultControl is Ownable, Pausable {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
//Vault Struct for Managed Assets
VaultAssets public vAssets;
//Pause Functions
/**
* @dev Emergency Call to stop all basic money flow functions.
*/
function pause() public onlyOwner {
_pause();
}
/**
* @dev Emergency Call to stop all basic money flow functions.
*/
function unpause() public onlyOwner {
_pause();
}
}
contract VaultBase is VaultControl {
// Internal functions
/**
* @dev Executes deposit operation with delegatecall.
* @param _amount: amount to be deposited
* @param _provider: address of provider to be used
*/
function _deposit(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("deposit(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes withdraw operation with delegatecall.
* @param _amount: amount to be withdrawn
* @param _provider: address of provider to be used
*/
function _withdraw(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("withdraw(address,uint256)", vAssets.collateralAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes borrow operation with delegatecall.
* @param _amount: amount to be borrowed
* @param _provider: address of provider to be used
*/
function _borrow(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("borrow(address,uint256)", vAssets.borrowAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Executes payback operation with delegatecall.
* @param _amount: amount to be paid back
* @param _provider: address of provider to be used
*/
function _payback(uint256 _amount, address _provider) internal {
bytes memory data =
abi.encodeWithSignature("payback(address,uint256)", vAssets.borrowAsset, _amount);
_execute(_provider, data);
}
/**
* @dev Returns byte response of delegatcalls
*/
function _execute(address _target, bytes memory _data)
internal
whenNotPaused
returns (bytes memory response)
{
/* solhint-disable */
assembly {
let succeeded := delegatecall(sub(gas(), 5000), _target, add(_data, 0x20), mload(_data), 0, 0)
let size := returndatasize()
response := mload(0x40)
mstore(0x40, add(response, and(add(add(size, 0x20), 0x1f), not(0x1f))))
mstore(response, size)
returndatacopy(add(response, 0x20), 0, size)
switch iszero(succeeded)
case 1 {
// throw if delegatecall failed
revert(add(response, 0x20), size)
}
}
/* solhint-disable */
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IFujiAdmin {
function getFlasher() external view returns (address);
function getFliquidator() external view returns (address);
function getController() external view returns (address);
function getTreasury() external view returns (address payable);
function getaWhiteList() external view returns (address);
function getVaultHarvester() external view returns (address);
function getBonusFlashL() external view returns (uint64, uint64);
function getBonusLiq() external view returns (uint64, uint64);
}
// 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;
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
);
}
// 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.12;
pragma experimental ABIEncoderV2;
interface IFujiERC1155 {
//Asset Types
enum AssetType {
//uint8 = 0
collateralToken,
//uint8 = 1
debtToken
}
//General Getter Functions
function getAssetID(AssetType _type, address _assetAddr) external view returns (uint256);
function qtyOfManagedAssets() external view returns (uint64);
function balanceOf(address _account, uint256 _id) external view returns (uint256);
//function splitBalanceOf(address account,uint256 _AssetID) external view returns (uint256,uint256);
//function balanceOfBatchType(address account, AssetType _Type) external view returns (uint256);
//Permit Controlled Functions
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external;
function burn(
address _account,
uint256 _id,
uint256 _amount
) external;
function updateState(uint256 _assetID, uint256 _newBalance) external;
function addInitializeAsset(AssetType _type, address _addr) external returns (uint64);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
interface IProvider {
//Basic Core Functions
function deposit(address _collateralAsset, uint256 _collateralAmount) external payable;
function borrow(address _borrowAsset, uint256 _borrowAmount) external payable;
function withdraw(address _collateralAsset, uint256 _collateralAmount) external payable;
function payback(address _borrowAsset, uint256 _borrowAmount) external payable;
// returns the borrow annualized rate for an asset in ray (1e27)
//Example 8.5% annual interest = 0.085 x 10^27 = 85000000000000000000000000 or 85*(10**24)
function getBorrowRateFor(address _asset) external view returns (uint256);
function getBorrowBalance(address _asset) external view returns (uint256);
function getDepositBalance(address _asset) external view returns (uint256);
function getBorrowBalanceOf(address _asset, address _who) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
interface IAlphaWhiteList {
function whiteListRoutine(
address _usrAddrs,
uint64 _assetId,
uint256 _amount,
address _erc1155
) external returns(bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity <0.8.0;
/**
* @title Errors library
* @author Fuji
* @notice Defines the error messages emitted by the different contracts of the Aave protocol
* @dev Error messages prefix glossary:
* - VL = Validation Logic 100 series
* - MATH = Math libraries 200 series
* - RF = Refinancing 300 series
* - VLT = vault 400 series
* - SP = Special 900 series
*/
library Errors {
//Errors
string public constant VL_INDEX_OVERFLOW = "100"; // index overflows uint128
string public constant VL_INVALID_MINT_AMOUNT = "101"; //invalid amount to mint
string public constant VL_INVALID_BURN_AMOUNT = "102"; //invalid amount to burn
string public constant VL_AMOUNT_ERROR = "103"; //Input value >0, and for ETH msg.value and amount shall match
string public constant VL_INVALID_WITHDRAW_AMOUNT = "104"; //Withdraw amount exceeds provided collateral, or falls undercollaterized
string public constant VL_INVALID_BORROW_AMOUNT = "105"; //Borrow amount does not meet collaterization
string public constant VL_NO_DEBT_TO_PAYBACK = "106"; //Msg sender has no debt amount to be payback
string public constant VL_MISSING_ERC20_ALLOWANCE = "107"; //Msg sender has not approved ERC20 full amount to transfer
string public constant VL_USER_NOT_LIQUIDATABLE = "108"; //User debt position is not liquidatable
string public constant VL_DEBT_LESS_THAN_AMOUNT = "109"; //User debt is less than amount to partial close
string public constant VL_PROVIDER_ALREADY_ADDED = "110"; // Provider is already added in Provider Array
string public constant VL_NOT_AUTHORIZED = "111"; //Not authorized
string public constant VL_INVALID_COLLATERAL = "112"; //There is no Collateral, or Collateral is not in active in vault
string public constant VL_NO_ERC20_BALANCE = "113"; //User does not have ERC20 balance
string public constant VL_INPUT_ERROR = "114"; //Check inputs. For ERC1155 batch functions, array sizes should match.
string public constant VL_ASSET_EXISTS = "115"; //Asset intended to be added already exists in FujiERC1155
string public constant VL_ZERO_ADDR_1155 = "116"; //ERC1155: balance/transfer for zero address
string public constant VL_NOT_A_CONTRACT = "117"; //Address is not a contract.
string public constant VL_INVALID_ASSETID_1155 = "118"; //ERC1155 Asset ID is invalid.
string public constant VL_NO_ERC1155_BALANCE = "119"; //ERC1155: insufficient balance for transfer.
string public constant VL_MISSING_ERC1155_APPROVAL = "120"; //ERC1155: transfer caller is not owner nor approved.
string public constant VL_RECEIVER_REJECT_1155 = "121"; //ERC1155Receiver rejected tokens
string public constant VL_RECEIVER_CONTRACT_NON_1155 = "122"; //ERC1155: transfer to non ERC1155Receiver implementer
string public constant VL_OPTIMIZER_FEE_SMALL = "123"; //Fuji OptimizerFee has to be > 1 RAY (1e27)
string public constant VL_UNDERCOLLATERIZED_ERROR = "124"; // Flashloan-Flashclose cannot be used when User's collateral is worth less than intended debt position to close.
string public constant VL_MINIMUM_PAYBACK_ERROR = "125"; // Minimum Amount payback should be at least Fuji Optimizerfee accrued interest.
string public constant VL_HARVESTING_FAILED = "126"; //Harvesting Function failed, check provided _farmProtocolNum or no claimable balance.
string public constant MATH_DIVISION_BY_ZERO = "201";
string public constant MATH_ADDITION_OVERFLOW = "202";
string public constant MATH_MULTIPLICATION_OVERFLOW = "203";
string public constant RF_NO_GREENLIGHT = "300"; // Conditions for refinancing are not met, greenLight, deltaAPRThreshold, deltatimestampThreshold
string public constant RF_INVALID_RATIO_VALUES = "301"; // Ratio Value provided is invalid, _ratioA/_ratioB <= 1, and > 0, or activeProvider borrowBalance = 0
string public constant RF_CHECK_RATES_FALSE = "302"; //Check Rates routine returned False
string public constant VLT_CALLER_MUST_BE_VAULT = "401"; // The caller of this function must be a vault
string public constant SP_ALPHA_WHITELIST = "901"; // One ETH cap value for Alpha Version < 1 ETH
}
// 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";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
library UniERC20 {
using SafeERC20 for IERC20;
IERC20 private constant _ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
IERC20 private constant _ZERO_ADDRESS = IERC20(0);
function isETH(IERC20 token) internal pure returns (bool) {
return (token == _ZERO_ADDRESS || token == _ETH_ADDRESS);
}
function uniBalanceOf(IERC20 token, address account) internal view returns (uint256) {
if (isETH(token)) {
return account.balance;
} else {
return token.balanceOf(account);
}
}
function uniTransfer(
IERC20 token,
address payable to,
uint256 amount
) internal {
if (amount > 0) {
if (isETH(token)) {
to.transfer(amount);
} else {
token.safeTransfer(to, amount);
}
}
}
function uniApprove(
IERC20 token,
address to,
uint256 amount
) internal {
require(!isETH(token), "Approve called on ETH");
if (amount == 0) {
token.safeApprove(to, 0);
} else {
uint256 allowance = token.allowance(address(this), to);
if (allowance < amount) {
if (allowance > 0) {
token.safeApprove(to, 0);
}
token.safeApprove(to, amount);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./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.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHUSDC is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == owner() || msg.sender == _fujiAdmin.getController(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // USDC
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 _fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
(_flashLoanAmount).mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(_fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into account all balances across providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of USDC in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(1e12).mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) external onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import { IVault } from "./IVault.sol";
import { VaultBase } from "./VaultBase.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {
AggregatorV3Interface
} from "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiERC1155 } from "../FujiERC1155/IFujiERC1155.sol";
import { IProvider } from "../Providers/IProvider.sol";
import { IAlphaWhiteList } from "../IAlphaWhiteList.sol";
import { Errors } from "../Libraries/Errors.sol";
interface IVaultHarvester {
function collectRewards(uint256 _farmProtocolNum) external returns (address claimedToken);
}
contract VaultETHDAI is IVault, VaultBase, ReentrancyGuard {
uint256 internal constant _BASE = 1e18;
struct Factor {
uint64 a;
uint64 b;
}
// Safety factor
Factor public safetyF;
// Collateralization factor
Factor public collatF;
//State variables
address[] public providers;
address public override activeProvider;
IFujiAdmin private _fujiAdmin;
address public override fujiERC1155;
AggregatorV3Interface public oracle;
modifier isAuthorized() {
require(
msg.sender == owner() || msg.sender == _fujiAdmin.getController(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
vAssets.collateralAsset = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); // ETH
vAssets.borrowAsset = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI
// 1.05
safetyF.a = 21;
safetyF.b = 20;
// 1.269
collatF.a = 80;
collatF.b = 63;
}
receive() external payable {}
//Core functions
/**
* @dev Deposits collateral and borrows underlying in a single function call from activeProvider
* @param _collateralAmount: amount to be deposited
* @param _borrowAmount: amount to be borrowed
*/
function depositAndBorrow(uint256 _collateralAmount, uint256 _borrowAmount) external payable {
deposit(_collateralAmount);
borrow(_borrowAmount);
}
/**
* @dev Paybacks the underlying asset and withdraws collateral in a single function call from activeProvider
* @param _paybackAmount: amount of underlying asset to be payback, pass -1 to pay full amount
* @param _collateralAmount: amount of collateral to be withdrawn, pass -1 to withdraw maximum amount
*/
function paybackAndWithdraw(int256 _paybackAmount, int256 _collateralAmount) external payable {
payback(_paybackAmount);
withdraw(_collateralAmount);
}
/**
* @dev Deposit Vault's type collateral to activeProvider
* call Controller checkrates
* @param _collateralAmount: to be deposited
* Emits a {Deposit} event.
*/
function deposit(uint256 _collateralAmount) public payable override {
require(msg.value == _collateralAmount && _collateralAmount != 0, Errors.VL_AMOUNT_ERROR);
// Alpha Whitelist Routine
require(
IAlphaWhiteList(_fujiAdmin.getaWhiteList()).whiteListRoutine(
msg.sender,
vAssets.collateralID,
_collateralAmount,
fujiERC1155
),
Errors.SP_ALPHA_WHITELIST
);
// Delegate Call Deposit to current provider
_deposit(_collateralAmount, address(activeProvider));
// Collateral Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.collateralID, _collateralAmount, "");
emit Deposit(msg.sender, vAssets.collateralAsset, _collateralAmount);
}
/**
* @dev Withdraws Vault's type collateral from activeProvider
* call Controller checkrates
* @param _withdrawAmount: amount of collateral to withdraw
* otherwise pass -1 to withdraw maximum amount possible of collateral (including safety factors)
* Emits a {Withdraw} event.
*/
function withdraw(int256 _withdrawAmount) public override nonReentrant {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
// Get User Collateral in this Vault
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Check User has collateral
require(providedCollateral > 0, Errors.VL_INVALID_COLLATERAL);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID),
true
);
uint256 amountToWithdraw =
_withdrawAmount < 0 ? providedCollateral.sub(neededCollateral) : uint256(_withdrawAmount);
// Check Withdrawal amount, and that it will not fall undercollaterized.
require(
amountToWithdraw != 0 && providedCollateral.sub(amountToWithdraw) >= neededCollateral,
Errors.VL_INVALID_WITHDRAW_AMOUNT
);
// Collateral Management before Withdraw Operation
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.collateralID, amountToWithdraw);
// Delegate Call Withdraw to current provider
_withdraw(amountToWithdraw, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, amountToWithdraw);
emit Withdraw(msg.sender, vAssets.collateralAsset, amountToWithdraw);
} else {
// Logic used when called by Fliquidator
_withdraw(uint256(_withdrawAmount), address(activeProvider));
IERC20(vAssets.collateralAsset).uniTransfer(msg.sender, uint256(_withdrawAmount));
}
}
/**
* @dev Borrows Vault's type underlying amount from activeProvider
* @param _borrowAmount: token amount of underlying to borrow
* Emits a {Borrow} event.
*/
function borrow(uint256 _borrowAmount) public override nonReentrant {
updateF1155Balances();
uint256 providedCollateral =
IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.collateralID);
// Get Required Collateral with Factors to maintain debt position healthy
uint256 neededCollateral =
getNeededCollateralFor(
_borrowAmount.add(IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID)),
true
);
// Check Provided Collateral is not Zero, and greater than needed to maintain healthy position
require(
_borrowAmount != 0 && providedCollateral > neededCollateral,
Errors.VL_INVALID_BORROW_AMOUNT
);
// Debt Management
IFujiERC1155(fujiERC1155).mint(msg.sender, vAssets.borrowID, _borrowAmount, "");
// Delegate Call Borrow to current provider
_borrow(_borrowAmount, address(activeProvider));
// Transer Assets to User
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _borrowAmount);
emit Borrow(msg.sender, vAssets.borrowAsset, _borrowAmount);
}
/**
* @dev Paybacks Vault's type underlying to activeProvider
* @param _repayAmount: token amount of underlying to repay, or pass -1 to repay full ammount
* Emits a {Repay} event.
*/
function payback(int256 _repayAmount) public payable override {
// If call from Normal User do typical, otherwise Fliquidator
if (msg.sender != _fujiAdmin.getFliquidator()) {
updateF1155Balances();
uint256 userDebtBalance = IFujiERC1155(fujiERC1155).balanceOf(msg.sender, vAssets.borrowID);
// Check User Debt is greater than Zero and amount is not Zero
require(_repayAmount != 0 && userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// If passed argument amount is negative do MAX
uint256 amountToPayback = _repayAmount < 0 ? userDebtBalance : uint256(_repayAmount);
// Check User Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= amountToPayback,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer Asset from User to Vault
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), amountToPayback);
// Delegate Call Payback to current provider
_payback(amountToPayback, address(activeProvider));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Debt Management
IFujiERC1155(fujiERC1155).burn(msg.sender, vAssets.borrowID, amountToPayback);
emit Payback(msg.sender, vAssets.borrowAsset, userDebtBalance);
} else {
// Logic used when called by Fliquidator
_payback(uint256(_repayAmount), address(activeProvider));
}
}
/**
* @dev Changes Vault debt and collateral to newProvider, called by Flasher
* @param _newProvider new provider's address
* @param _flashLoanAmount amount of flashloan underlying to repay Flashloan
* Emits a {Switch} event.
*/
function executeSwitch(
address _newProvider,
uint256 _flashLoanAmount,
uint256 _fee
) external override onlyFlash whenNotPaused {
// Compute Ratio of transfer before payback
uint256 ratio =
_flashLoanAmount.mul(1e18).div(
IProvider(activeProvider).getBorrowBalance(vAssets.borrowAsset)
);
// Payback current provider
_payback(_flashLoanAmount, activeProvider);
// Withdraw collateral proportional ratio from current provider
uint256 collateraltoMove =
IProvider(activeProvider).getDepositBalance(vAssets.collateralAsset).mul(ratio).div(1e18);
_withdraw(collateraltoMove, activeProvider);
// Deposit to the new provider
_deposit(collateraltoMove, _newProvider);
// Borrow from the new provider, borrowBalance + premium
_borrow(_flashLoanAmount.add(_fee), _newProvider);
// return borrowed amount to Flasher
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, _flashLoanAmount.add(_fee));
emit Switch(address(this), activeProvider, _newProvider, _flashLoanAmount, collateraltoMove);
}
//Setter, change state functions
/**
* @dev Sets a new active provider for the Vault
* @param _provider: fuji address of the new provider
* Emits a {SetActiveProvider} event.
*/
function setActiveProvider(address _provider) external override isAuthorized {
activeProvider = _provider;
emit SetActiveProvider(_provider);
}
//Administrative functions
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Sets a fujiERC1155 Collateral and Debt Asset manager for this vault and initializes it.
* @param _fujiERC1155: fuji ERC1155 address
*/
function setFujiERC1155(address _fujiERC1155) external isAuthorized {
fujiERC1155 = _fujiERC1155;
vAssets.collateralID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.collateralToken,
address(this)
);
vAssets.borrowID = IFujiERC1155(_fujiERC1155).addInitializeAsset(
IFujiERC1155.AssetType.debtToken,
address(this)
);
}
/**
* @dev Set Factors "a" and "b" for a Struct Factor
* For safetyF; Sets Safety Factor of Vault, should be > 1, a/b
* For collatF; Sets Collateral Factor of Vault, should be > 1, a/b
* @param _newFactorA: Nominator
* @param _newFactorB: Denominator
* @param _isSafety: safetyF or collatF
*/
function setFactor(
uint64 _newFactorA,
uint64 _newFactorB,
bool _isSafety
) external isAuthorized {
if (_isSafety) {
safetyF.a = _newFactorA;
safetyF.b = _newFactorB;
} else {
collatF.a = _newFactorA;
collatF.b = _newFactorB;
}
}
/**
* @dev Sets the Oracle address (Must Comply with AggregatorV3Interface)
* @param _oracle: new Oracle address
*/
function setOracle(address _oracle) external isAuthorized {
oracle = AggregatorV3Interface(_oracle);
}
/**
* @dev Set providers to the Vault
* @param _providers: new providers' addresses
*/
function setProviders(address[] calldata _providers) external isAuthorized {
providers = _providers;
}
/**
* @dev External Function to call updateState in F1155
*/
function updateF1155Balances() public override {
uint256 borrowBals;
uint256 depositBals;
// take into balances across all providers
uint256 length = providers.length;
for (uint256 i = 0; i < length; i++) {
borrowBals = borrowBals.add(IProvider(providers[i]).getBorrowBalance(vAssets.borrowAsset));
}
for (uint256 i = 0; i < length; i++) {
depositBals = depositBals.add(
IProvider(providers[i]).getDepositBalance(vAssets.collateralAsset)
);
}
IFujiERC1155(fujiERC1155).updateState(vAssets.borrowID, borrowBals);
IFujiERC1155(fujiERC1155).updateState(vAssets.collateralID, depositBals);
}
//Getter Functions
/**
* @dev Returns an array of the Vault's providers
*/
function getProviders() external view override returns (address[] memory) {
return providers;
}
/**
* @dev Returns an amount to be paid as bonus for liquidation
* @param _amount: Vault underlying type intended to be liquidated
* @param _flash: Flash or classic type of liquidation, bonus differs
*/
function getLiquidationBonusFor(uint256 _amount, bool _flash)
external
view
override
returns (uint256)
{
if (_flash) {
// Bonus Factors for Flash Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusFlashL();
return _amount.mul(a).div(b);
} else {
//Bonus Factors for Normal Liquidation
(uint64 a, uint64 b) = _fujiAdmin.getBonusLiq();
return _amount.mul(a).div(b);
}
}
/**
* @dev Returns the amount of collateral needed, including or not safety factors
* @param _amount: Vault underlying type intended to be borrowed
* @param _withFactors: Inidicate if computation should include safety_Factors
*/
function getNeededCollateralFor(uint256 _amount, bool _withFactors)
public
view
override
returns (uint256)
{
// Get price of DAI in ETH
(, int256 latestPrice, , , ) = oracle.latestRoundData();
uint256 minimumReq = (_amount.mul(uint256(latestPrice))).div(_BASE);
if (_withFactors) {
return minimumReq.mul(collatF.a).mul(safetyF.a).div(collatF.b).div(safetyF.b);
} else {
return minimumReq;
}
}
/**
* @dev Returns the borrow balance of the Vault's underlying at a particular provider
* @param _provider: address of a provider
*/
function borrowBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getBorrowBalance(vAssets.borrowAsset);
}
/**
* @dev Returns the deposit balance of the Vault's type collateral at a particular provider
* @param _provider: address of a provider
*/
function depositBalance(address _provider) external view override returns (uint256) {
return IProvider(_provider).getDepositBalance(vAssets.collateralAsset);
}
/**
* @dev Harvests the Rewards from baseLayer Protocols
* @param _farmProtocolNum: number per VaultHarvester Contract for specific farm
*/
function harvestRewards(uint256 _farmProtocolNum) external onlyOwner {
address tokenReturned =
IVaultHarvester(_fujiAdmin.getVaultHarvester()).collectRewards(_farmProtocolNum);
uint256 tokenBal = IERC20(tokenReturned).balanceOf(address(this));
require(tokenReturned != address(0) && tokenBal > 0, Errors.VL_HARVESTING_FAILED);
IERC20(tokenReturned).uniTransfer(payable(_fujiAdmin.getTreasury()), tokenBal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.8.0;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface LQTYInterface {}
contract LQTYHelpers {
function _initializeTrouve() internal {
//TODO function
}
}
contract ProviderLQTY is IProvider, LQTYHelpers {
using SafeMath for uint256;
using UniERC20 for IERC20;
function deposit(address collateralAsset, uint256 collateralAmount) external payable override {
collateralAsset;
collateralAmount;
//TODO
}
function borrow(address borrowAsset, uint256 borrowAmount) external payable override {
borrowAsset;
borrowAmount;
//TODO
}
function withdraw(address collateralAsset, uint256 collateralAmount) external payable override {
collateralAsset;
collateralAmount;
//TODO
}
function payback(address borrowAsset, uint256 borrowAmount) external payable override {
borrowAsset;
borrowAmount;
//TODO
}
function getBorrowRateFor(address asset) external view override returns (uint256) {
asset;
//TODO
return 0;
}
function getBorrowBalance(address _asset) external view override returns (uint256) {
_asset;
//TODO
return 0;
}
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
_asset;
_who;
//TODO
return 0;
}
function getDepositBalance(address _asset) external view override returns (uint256) {
_asset;
//TODO
return 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IWethERC20 is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
interface SoloMarginContract {
struct Info {
address owner;
uint256 number;
}
struct Price {
uint256 value;
}
struct Value {
uint256 value;
}
struct Rate {
uint256 value;
}
enum ActionType { Deposit, Withdraw, Transfer, Buy, Sell, Trade, Liquidate, Vaporize, Call }
enum AssetDenomination { Wei, Par }
enum AssetReference { Delta, Target }
struct AssetAmount {
bool sign;
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
struct Wei {
bool sign;
uint256 value;
}
function operate(Info[] calldata _accounts, ActionArgs[] calldata _actions) external;
function getAccountWei(Info calldata _account, uint256 _marketId)
external
view
returns (Wei memory);
function getNumMarkets() external view returns (uint256);
function getMarketTokenAddress(uint256 _marketId) external view returns (address);
function getAccountValues(Info memory _account)
external
view
returns (Value memory, Value memory);
function getMarketInterestRate(uint256 _marketId) external view returns (Rate memory);
}
contract HelperFunct {
/**
* @dev get Dydx Solo Address
*/
function getDydxAddress() public pure returns (address addr) {
addr = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
}
/**
* @dev get WETH address
*/
function getWETHAddr() public pure returns (address weth) {
weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
}
/**
* @dev Return ethereum address
*/
function _getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
/**
* @dev Get Dydx Market ID from token Address
*/
function _getMarketId(SoloMarginContract _solo, address _token)
internal
view
returns (uint256 _marketId)
{
uint256 markets = _solo.getNumMarkets();
address token = _token == _getEthAddr() ? getWETHAddr() : _token;
bool check = false;
for (uint256 i = 0; i < markets; i++) {
if (token == _solo.getMarketTokenAddress(i)) {
_marketId = i;
check = true;
break;
}
}
require(check, "DYDX Market doesnt exist!");
}
/**
* @dev Get Dydx Acccount arg
*/
function _getAccountArgs() internal view returns (SoloMarginContract.Info[] memory) {
SoloMarginContract.Info[] memory accounts = new SoloMarginContract.Info[](1);
accounts[0] = (SoloMarginContract.Info(address(this), 0));
return accounts;
}
/**
* @dev Get Dydx Actions args.
*/
function _getActionsArgs(
uint256 _marketId,
uint256 _amt,
bool _sign
) internal view returns (SoloMarginContract.ActionArgs[] memory) {
SoloMarginContract.ActionArgs[] memory actions = new SoloMarginContract.ActionArgs[](1);
SoloMarginContract.AssetAmount memory amount =
SoloMarginContract.AssetAmount(
_sign,
SoloMarginContract.AssetDenomination.Wei,
SoloMarginContract.AssetReference.Delta,
_amt
);
bytes memory empty;
SoloMarginContract.ActionType action =
_sign ? SoloMarginContract.ActionType.Deposit : SoloMarginContract.ActionType.Withdraw;
actions[0] = SoloMarginContract.ActionArgs(
action,
0,
amount,
_marketId,
0,
address(this),
0,
empty
);
return actions;
}
}
contract ProviderDYDX is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
bool public donothing = true;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.deposit{ value: _amount }();
tweth.approve(getDydxAddress(), _amount);
} else {
IWethERC20 tweth = IWethERC20(_asset);
tweth.approve(getDydxAddress(), _amount);
}
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true));
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false));
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.approve(address(tweth), _amount);
tweth.withdraw(_amount);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, false));
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.approve(address(_asset), _amount);
tweth.withdraw(_amount);
}
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
if (_asset == _getEthAddr()) {
IWethERC20 tweth = IWethERC20(getWETHAddr());
tweth.deposit{ value: _amount }();
tweth.approve(getDydxAddress(), _amount);
} else {
IWethERC20 tweth = IWethERC20(_asset);
tweth.approve(getDydxAddress(), _amount);
}
dydxContract.operate(_getAccountArgs(), _getActionsArgs(marketId, _amount, true));
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Rate memory _rate = dydxContract.getMarketInterestRate(marketId);
return (_rate.value).mul(1e9).mul(365 days);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account =
SoloMarginContract.Info({ owner: msg.sender, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
* @param _who: address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account = SoloMarginContract.Info({ owner: _who, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
SoloMarginContract dydxContract = SoloMarginContract(getDydxAddress());
uint256 marketId = _getMarketId(dydxContract, _asset);
SoloMarginContract.Info memory account =
SoloMarginContract.Info({ owner: msg.sender, number: 0 });
SoloMarginContract.Wei memory structbalance = dydxContract.getAccountWei(account, marketId);
return structbalance.value;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface IGenCToken is IERC20 {
function redeem(uint256) external returns (uint256);
function redeemUnderlying(uint256) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function borrowRatePerBlock() external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function getCash() external view returns (uint256);
}
interface ICErc20 is IGenCToken {
function mint(uint256) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
}
interface ICEth is IGenCToken {
function mint() external payable;
function repayBorrow() external payable;
function repayBorrowBehalf(address borrower) external payable;
}
interface IComptroller {
function markets(address) external returns (bool, uint256);
function enterMarkets(address[] calldata) external returns (uint256[] memory);
function exitMarket(address cTokenAddress) external returns (uint256);
function getAccountLiquidity(address)
external
view
returns (
uint256,
uint256,
uint256
);
}
interface IFujiMappings {
function addressMapping(address) external view returns (address);
}
contract HelperFunct {
function _isETH(address token) internal pure returns (bool) {
return (token == address(0) || token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE));
}
function _getMappingAddr() internal pure returns (address) {
return 0x6b09443595BFb8F91eA837c7CB4Fe1255782093b;
}
function _getComptrollerAddress() internal pure returns (address) {
return 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B;
}
//Compound functions
/**
* @dev Approves vault's assets as collateral for Compound Protocol.
* @param _cTokenAddress: asset type to be approved as collateral.
*/
function _enterCollatMarket(address _cTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
address[] memory cTokenMarkets = new address[](1);
cTokenMarkets[0] = _cTokenAddress;
comptroller.enterMarkets(cTokenMarkets);
}
/**
* @dev Removes vault's assets as collateral for Compound Protocol.
* @param _cTokenAddress: asset type to be removed as collateral.
*/
function _exitCollatMarket(address _cTokenAddress) internal {
// Create a reference to the corresponding network Comptroller
IComptroller comptroller = IComptroller(_getComptrollerAddress());
comptroller.exitMarket(_cTokenAddress);
}
}
contract ProviderCompound is IProvider, HelperFunct {
using SafeMath for uint256;
using UniERC20 for IERC20;
//Provider Core Functions
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset: token address to deposit. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Enter and/or ensure collateral market is enacted
_enterCollatMarket(cTokenAddr);
if (_isETH(_asset)) {
// Create a reference to the cToken contract
ICEth cToken = ICEth(cTokenAddr);
//Compound protocol Mints cTokens, ETH method
cToken.mint{ value: _amount }();
} else {
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the cToken contract
ICErc20 cToken = ICErc20(cTokenAddr);
//Checks, Vault balance of ERC20 to make deposit
require(erc20token.balanceOf(address(this)) >= _amount, "Not enough Balance");
//Approve to move ERC20tokens
erc20token.uniApprove(address(cTokenAddr), _amount);
// Compound Protocol mints cTokens, trhow error if not
require(cToken.mint(_amount) == 0, "Deposit-failed");
}
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset: token address to withdraw. (For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cToken contract
IGenCToken cToken = IGenCToken(cTokenAddr);
//Compound Protocol Redeem Process, throw errow if not.
require(cToken.redeemUnderlying(_amount) == 0, "Withdraw-failed");
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
// Create a reference to the corresponding cToken contract
IGenCToken cToken = IGenCToken(cTokenAddr);
//Enter and/or ensure collateral market is enacted
//_enterCollatMarket(cTokenAddr);
//Compound Protocol Borrow Process, throw errow if not.
require(cToken.borrow(_amount) == 0, "borrow-failed");
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount: token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
//Get cToken address from mapping
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
if (_isETH(_asset)) {
// Create a reference to the corresponding cToken contract
ICEth cToken = ICEth(cTokenAddr);
cToken.repayBorrow{ value: msg.value }();
} else {
// Create reference to the ERC20 contract
IERC20 erc20token = IERC20(_asset);
// Create a reference to the corresponding cToken contract
ICErc20 cToken = ICErc20(cTokenAddr);
// Check there is enough balance to pay
require(erc20token.balanceOf(address(this)) >= _amount, "Not-enough-token");
erc20token.uniApprove(address(cTokenAddr), _amount);
cToken.repayBorrow(_amount);
}
}
/**
* @dev Returns the current borrowing rate (APR) of a ETH/ERC20_Token, in ray(1e27).
* @param _asset: token address to query the current borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
//Block Rate transformed for common mantissa for Fuji in ray (1e27), Note: Compound uses base 1e18
uint256 bRateperBlock = (IGenCToken(cTokenAddr).borrowRatePerBlock()).mul(10**9);
// The approximate number of blocks per year that is assumed by the Compound interest rate model
uint256 blocksperYear = 2102400;
return bRateperBlock.mul(blocksperYear);
}
/**
* @dev Returns the borrow balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCToken(cTokenAddr).borrowBalanceStored(msg.sender);
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* This function is the accurate way to get Compound borrow balance.
* It costs ~84K gas and is not a view function.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
return IGenCToken(cTokenAddr).borrowBalanceCurrent(_who);
}
/**
* @dev Returns the deposit balance of a ETH/ERC20_Token.
* @param _asset: token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
address cTokenAddr = IFujiMappings(_getMappingAddr()).addressMapping(_asset);
uint256 cTokenBal = IGenCToken(cTokenAddr).balanceOf(msg.sender);
uint256 exRate = IGenCToken(cTokenAddr).exchangeRateStored();
return exRate.mul(cTokenBal).div(1e18);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.0;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IProvider } from "./IProvider.sol";
interface ITokenInterface {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
}
interface IAaveInterface {
function deposit(
address _asset,
uint256 _amount,
address _onBehalfOf,
uint16 _referralCode
) external;
function withdraw(
address _asset,
uint256 _amount,
address _to
) external;
function borrow(
address _asset,
uint256 _amount,
uint256 _interestRateMode,
uint16 _referralCode,
address _onBehalfOf
) external;
function repay(
address _asset,
uint256 _amount,
uint256 _rateMode,
address _onBehalfOf
) external;
function setUserUseReserveAsCollateral(address _asset, bool _useAsCollateral) external;
}
interface AaveLendingPoolProviderInterface {
function getLendingPool() external view returns (address);
}
interface AaveDataProviderInterface {
function getReserveTokensAddresses(address _asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
function getUserReserveData(address _asset, address _user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveData(address _asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}
interface AaveAddressProviderRegistryInterface {
function getAddressesProvidersList() external view returns (address[] memory);
}
contract ProviderAave is IProvider {
using SafeMath for uint256;
using UniERC20 for IERC20;
function _getAaveProvider() internal pure returns (AaveLendingPoolProviderInterface) {
return AaveLendingPoolProviderInterface(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); //mainnet
}
function _getAaveDataProvider() internal pure returns (AaveDataProviderInterface) {
return AaveDataProviderInterface(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d); //mainnet
}
function _getWethAddr() internal pure returns (address) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Mainnet WETH Address
}
function _getEthAddr() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; // ETH Address
}
function _getIsColl(
AaveDataProviderInterface _aaveData,
address _token,
address _user
) internal view returns (bool isCol) {
(, , , , , , , , isCol) = _aaveData.getUserReserveData(_token, _user);
}
function _convertEthToWeth(
bool _isEth,
ITokenInterface _token,
uint256 _amount
) internal {
if (_isEth) _token.deposit{ value: _amount }();
}
function _convertWethToEth(
bool _isEth,
ITokenInterface _token,
uint256 _amount
) internal {
if (_isEth) {
_token.approve(address(_token), _amount);
_token.withdraw(_amount);
}
}
/**
* @dev Return the borrowing rate of ETH/ERC20_Token.
* @param _asset to query the borrowing rate.
*/
function getBorrowRateFor(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
(, , , , uint256 variableBorrowRate, , , , , ) =
AaveDataProviderInterface(aaveData).getReserveData(
_asset == _getEthAddr() ? _getWethAddr() : _asset
);
return variableBorrowRate;
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
*/
function getBorrowBalance(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, msg.sender);
return variableDebt;
}
/**
* @dev Return borrow balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
* @param _who address of the account.
*/
function getBorrowBalanceOf(address _asset, address _who) external override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, _who);
return variableDebt;
}
/**
* @dev Return deposit balance of ETH/ERC20_Token.
* @param _asset token address to query the balance.
*/
function getDepositBalance(address _asset) external view override returns (uint256) {
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
(uint256 atokenBal, , , , , , , , ) = aaveData.getUserReserveData(_token, msg.sender);
return atokenBal;
}
/**
* @dev Deposit ETH/ERC20_Token.
* @param _asset token address to deposit.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount token amount to deposit.
*/
function deposit(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
if (isEth) {
_amount = _amount == uint256(-1) ? address(this).balance : _amount;
_convertEthToWeth(isEth, tokenContract, _amount);
} else {
_amount = _amount == uint256(-1) ? tokenContract.balanceOf(address(this)) : _amount;
}
tokenContract.approve(address(aave), _amount);
aave.deposit(_token, _amount, address(this), 0);
if (!_getIsColl(aaveData, _token, address(this))) {
aave.setUserUseReserveAsCollateral(_token, true);
}
}
/**
* @dev Borrow ETH/ERC20_Token.
* @param _asset token address to borrow.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param _amount token amount to borrow.
*/
function borrow(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
aave.borrow(_token, _amount, 2, 0, address(this));
_convertWethToEth(isEth, ITokenInterface(_token), _amount);
}
/**
* @dev Withdraw ETH/ERC20_Token.
* @param _asset token address to withdraw.
* @param _amount token amount to withdraw.
*/
function withdraw(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
uint256 initialBal = tokenContract.balanceOf(address(this));
aave.withdraw(_token, _amount, address(this));
uint256 finalBal = tokenContract.balanceOf(address(this));
_amount = finalBal.sub(initialBal);
_convertWethToEth(isEth, tokenContract, _amount);
}
/**
* @dev Payback borrowed ETH/ERC20_Token.
* @param _asset token address to payback.
* @param _amount token amount to payback.
*/
function payback(address _asset, uint256 _amount) external payable override {
IAaveInterface aave = IAaveInterface(_getAaveProvider().getLendingPool());
AaveDataProviderInterface aaveData = _getAaveDataProvider();
bool isEth = _asset == _getEthAddr();
address _token = isEth ? _getWethAddr() : _asset;
ITokenInterface tokenContract = ITokenInterface(_token);
(, , uint256 variableDebt, , , , , , ) = aaveData.getUserReserveData(_token, address(this));
_amount = _amount == uint256(-1) ? variableDebt : _amount;
if (isEth) _convertEthToWeth(isEth, tokenContract, _amount);
tokenContract.approve(address(aave), _amount);
aave.repay(_token, _amount, 2, address(this));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { WadRayMath } from "./WadRayMath.sol";
library MathUtils {
using SafeMath for uint256;
using WadRayMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant _SECONDS_PER_YEAR = 365 days;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solhint-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));
return (rate.mul(timeDifference) / _SECONDS_PER_YEAR).add(WadRayMath.ray());
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solhint-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / _SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solhint-disable-next-line
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import { Errors } from "./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 _HALF_WAD = _WAD / 2;
uint256 internal constant _RAY = 1e27;
uint256 internal constant _HALF_RAY = _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 _HALF_RAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return _HALF_WAD;
}
/**
* @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 - _HALF_WAD) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_WAD) / _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 - _HALF_RAY) / b, Errors.MATH_MULTIPLICATION_OVERFLOW);
return (a * b + _HALF_RAY) / _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: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IFujiERC1155 } from "./IFujiERC1155.sol";
import { FujiBaseERC1155 } from "./FujiBaseERC1155.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { WadRayMath } from "../Libraries/WadRayMath.sol";
import { MathUtils } from "../Libraries/MathUtils.sol";
import { Errors } from "../Libraries/Errors.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
contract F1155Manager is Ownable {
using Address for address;
// Controls for Mint-Burn Operations
mapping(address => bool) public addrPermit;
modifier onlyPermit() {
require(addrPermit[_msgSender()] || msg.sender == owner(), Errors.VL_NOT_AUTHORIZED);
_;
}
function setPermit(address _address, bool _permit) public onlyOwner {
require((_address).isContract(), Errors.VL_NOT_A_CONTRACT);
addrPermit[_address] = _permit;
}
}
contract FujiERC1155 is IFujiERC1155, FujiBaseERC1155, F1155Manager {
using WadRayMath for uint256;
//FujiERC1155 Asset ID Mapping
//AssetType => asset reference address => ERC1155 Asset ID
mapping(AssetType => mapping(address => uint256)) public assetIDs;
//Control mapping that returns the AssetType of an AssetID
mapping(uint256 => AssetType) public assetIDtype;
uint64 public override qtyOfManagedAssets;
//Asset ID Liquidity Index mapping
//AssetId => Liquidity index for asset ID
mapping(uint256 => uint256) public indexes;
// Optimizer Fee expressed in Ray, where 1 ray = 100% APR
//uint256 public optimizerFee;
//uint256 public lastUpdateTimestamp;
//uint256 public fujiIndex;
/// @dev Ignoring leap years
//uint256 internal constant SECONDS_PER_YEAR = 365 days;
constructor() public {
//fujiIndex = WadRayMath.ray();
//optimizerFee = 1e24;
}
/**
* @dev Updates Index of AssetID
* @param _assetID: ERC1155 ID of the asset which state will be updated.
* @param newBalance: Amount
**/
function updateState(uint256 _assetID, uint256 newBalance) external override onlyPermit {
uint256 total = totalSupply(_assetID);
if (newBalance > 0 && total > 0 && newBalance > total) {
uint256 diff = newBalance.sub(total);
uint256 amountToIndexRatio = (diff.wadToRay()).rayDiv(total.wadToRay());
uint256 result = amountToIndexRatio.add(WadRayMath.ray());
result = result.rayMul(indexes[_assetID]);
require(result <= type(uint128).max, Errors.VL_INDEX_OVERFLOW);
indexes[_assetID] = uint128(result);
// TODO: calculate interest rate for a fujiOptimizer Fee.
/*
if(lastUpdateTimestamp==0){
lastUpdateTimestamp = block.timestamp;
}
uint256 accrued = _calculateCompoundedInterest(
optimizerFee,
lastUpdateTimestamp,
block.timestamp
).rayMul(fujiIndex);
fujiIndex = accrued;
lastUpdateTimestamp = block.timestamp;
*/
}
}
/**
* @dev Returns the total supply of Asset_ID with accrued interest.
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function totalSupply(uint256 _assetID) public view virtual override returns (uint256) {
// TODO: include interest accrued by Fuji OptimizerFee
return super.totalSupply(_assetID).rayMul(indexes[_assetID]);
}
/**
* @dev Returns the scaled total supply of the token ID. Represents sum(token ID Principal /index)
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledTotalSupply(uint256 _assetID) public view virtual returns (uint256) {
return super.totalSupply(_assetID);
}
/**
* @dev Returns the principal + accrued interest balance of the user
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function balanceOf(address _account, uint256 _assetID)
public
view
override(FujiBaseERC1155, IFujiERC1155)
returns (uint256)
{
uint256 scaledBalance = super.balanceOf(_account, _assetID);
if (scaledBalance == 0) {
return 0;
}
// TODO: include interest accrued by Fuji OptimizerFee
return scaledBalance.rayMul(indexes[_assetID]);
}
/**
* @dev Returns the balance of User, split into owed amounts to BaseProtocol and FujiProtocol
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
/*
function splitBalanceOf(
address _account,
uint256 _assetID
) public view override returns (uint256,uint256) {
uint256 scaledBalance = super.balanceOf(_account, _assetID);
if (scaledBalance == 0) {
return (0,0);
} else {
TO DO COMPUTATION
return (baseprotocol, fuji);
}
}
*/
/**
* @dev Returns Scaled Balance of the user (e.g. balance/index)
* @param _account: address of the User
* @param _assetID: ERC1155 ID of the asset which state will be updated.
**/
function scaledBalanceOf(address _account, uint256 _assetID)
public
view
virtual
returns (uint256)
{
return super.balanceOf(_account, _assetID);
}
/**
* @dev Returns the sum of balance of the user for an AssetType.
* This function is used for when AssetType have units of account of the same value (e.g stablecoins)
* @param _account: address of the User
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
**/
/*
function balanceOfBatchType(address _account, AssetType _type) external view override returns (uint256 total) {
uint256[] memory IDs = engagedIDsOf(_account, _type);
for(uint i; i < IDs.length; i++ ){
total = total.add(balanceOf(_account, IDs[i]));
}
}
*/
/**
* @dev Mints tokens for Collateral and Debt receipts for the Fuji Protocol
* Emits a {TransferSingle} event.
* Requirements:
* - `_account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
* - `_amount` should be in WAD
*/
function mint(
address _account,
uint256 _id,
uint256 _amount,
bytes memory _data
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_id][_account] = accountBalance.add(amountScaled);
_totalSupply[_id] = assetTotalBalance.add(amountScaled);
emit TransferSingle(operator, address(0), _account, _id, _amount);
_doSafeTransferAcceptanceCheck(operator, address(0), _account, _id, _amount, _data);
}
/**
* @dev [Batched] version of {mint}.
* Requirements:
* - `_ids` and `_amounts` must have the same length.
* - If `_to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function mintBatch(
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data
) external onlyPermit {
require(_to != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
accountBalance = _balances[_ids[i]][_to];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0, Errors.VL_INVALID_MINT_AMOUNT);
_balances[_ids[i]][_to] = accountBalance.add(amountScaled);
_totalSupply[_ids[i]] = assetTotalBalance.add(amountScaled);
}
emit TransferBatch(operator, address(0), _to, _ids, _amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), _to, _ids, _amounts, _data);
}
/**
* @dev Destroys `_amount` receipt tokens of token type `_id` from `account` for the Fuji Protocol
* Requirements:
* - `account` cannot be the zero address.
* - `account` must have at least `_amount` tokens of token type `_id`.
* - `_amount` should be in WAD
*/
function burn(
address _account,
uint256 _id,
uint256 _amount
) external override onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
address operator = _msgSender();
uint256 accountBalance = _balances[_id][_account];
uint256 assetTotalBalance = _totalSupply[_id];
uint256 amountScaled = _amount.rayDiv(indexes[_id]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_id][_account] = accountBalance.sub(amountScaled);
_totalSupply[_id] = assetTotalBalance.sub(amountScaled);
emit TransferSingle(operator, _account, address(0), _id, _amount);
}
/**
* @dev [Batched] version of {burn}.
* Requirements:
* - `_ids` and `_amounts` must have the same length.
*/
function burnBatch(
address _account,
uint256[] memory _ids,
uint256[] memory _amounts
) external onlyPermit {
require(_account != address(0), Errors.VL_ZERO_ADDR_1155);
require(_ids.length == _amounts.length, Errors.VL_INPUT_ERROR);
address operator = _msgSender();
uint256 accountBalance;
uint256 assetTotalBalance;
uint256 amountScaled;
for (uint256 i = 0; i < _ids.length; i++) {
uint256 amount = _amounts[i];
accountBalance = _balances[_ids[i]][_account];
assetTotalBalance = _totalSupply[_ids[i]];
amountScaled = _amounts[i].rayDiv(indexes[_ids[i]]);
require(amountScaled != 0 && accountBalance >= amountScaled, Errors.VL_INVALID_BURN_AMOUNT);
_balances[_ids[i]][_account] = accountBalance.sub(amount);
_totalSupply[_ids[i]] = assetTotalBalance.sub(amount);
}
emit TransferBatch(operator, _account, address(0), _ids, _amounts);
}
//Getter Functions
/**
* @dev Getter Function for the Asset ID locally managed
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function getAssetID(AssetType _type, address _addr) external view override returns (uint256 id) {
id = assetIDs[_type][_addr];
require(id <= qtyOfManagedAssets, Errors.VL_INVALID_ASSETID_1155);
}
//Setter Functions
/**
* @dev Sets the FujiProtocol Fee to be charged
* @param _fee; Fee in Ray(1e27) to charge users for optimizerFee (1 ray = 100% APR)
*/
/*
function setoptimizerFee(uint256 _fee) public onlyOwner {
require(_fee >= WadRayMath.ray(), Errors.VL_OPTIMIZER_FEE_SMALL);
optimizerFee = _fee;
}
*/
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
*/
function setURI(string memory _newUri) public onlyOwner {
_uri = _newUri;
}
/**
* @dev Adds and initializes liquidity index of a new asset in FujiERC1155
* @param _type: enum AssetType, 0 = Collateral asset, 1 = debt asset
* @param _addr: Reference Address of the Asset
*/
function addInitializeAsset(AssetType _type, address _addr)
external
override
onlyPermit
returns (uint64)
{
require(assetIDs[_type][_addr] == 0, Errors.VL_ASSET_EXISTS);
assetIDs[_type][_addr] = qtyOfManagedAssets;
assetIDtype[qtyOfManagedAssets] = _type;
//Initialize the liquidity Index
indexes[qtyOfManagedAssets] = WadRayMath.ray();
qtyOfManagedAssets++;
return qtyOfManagedAssets - 1;
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param _rate The interest rate, in ray
* @param _lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
/*
function _calculateCompoundedInterest(
uint256 _rate,
uint256 _lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solium-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(_lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = _rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
*/
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import { IERC1155Receiver } from "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import { IERC1155MetadataURI } from "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol";
import { ERC165 } from "@openzeppelin/contracts/introspection/ERC165.sol";
import { IERC165 } from "@openzeppelin/contracts/introspection/IERC165.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { Context } from "@openzeppelin/contracts/utils/Context.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Errors } from "../Libraries/Errors.sol";
/**
*
* @dev Implementation of the Base ERC1155 multi-token standard functions
* for Fuji Protocol control of User collaterals and borrow debt positions.
* Originally based on Openzeppelin
*
*/
contract FujiBaseERC1155 is IERC1155, ERC165, Context {
using Address for address;
using SafeMath for uint256;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) internal _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) internal _operatorApprovals;
// Mapping from token ID to totalSupply
mapping(uint256 => uint256) internal _totalSupply;
//Fuji ERC1155 Transfer Control
bool public transfersActive;
modifier isTransferActive() {
require(transfersActive, Errors.VL_NOT_AUTHORIZED);
_;
}
//URI for all token types by relying on ID substitution
//https://token.fujiDao.org/{id}.json
string internal _uri;
/**
* @return The total supply of a token id
**/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
* Requirements:
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), Errors.VL_ZERO_ADDR_1155);
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
* Requirements:
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, Errors.VL_INPUT_ERROR);
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, Errors.VL_INPUT_ERROR);
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override isTransferActive {
require(to != address(0), Errors.VL_ZERO_ADDR_1155);
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
Errors.VL_MISSING_ERC1155_APPROVAL
);
address operator = _msgSender();
_beforeTokenTransfer(
operator,
from,
to,
_asSingletonArray(id),
_asSingletonArray(amount),
data
);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE);
_balances[id][from] = fromBalance.sub(amount);
_balances[id][to] = uint256(_balances[id][to]).add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override isTransferActive {
require(ids.length == amounts.length, Errors.VL_INPUT_ERROR);
require(to != address(0), Errors.VL_ZERO_ADDR_1155);
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
Errors.VL_MISSING_ERC1155_APPROVAL
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, Errors.VL_NO_ERC1155_BALANCE);
_balances[id][from] = fromBalance.sub(amount);
_balances[id][to] = uint256(_balances[id][to]).add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert(Errors.VL_RECEIVER_REJECT_1155);
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert(Errors.VL_RECEIVER_CONTRACT_NON_1155);
}
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { IVault } from "./Vaults/IVault.sol";
import { IFujiAdmin } from "./IFujiAdmin.sol";
import { IFujiERC1155 } from "./FujiERC1155/IFujiERC1155.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Flasher } from "./Flashloans/Flasher.sol";
import { FlashLoan } from "./Flashloans/LibFlashLoan.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Errors } from "./Libraries/Errors.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "./Libraries/LibUniERC20.sol";
import {
IUniswapV2Router02
} from "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
interface IVaultExt is IVault {
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
function vAssets() external view returns (VaultAssets memory);
}
contract Fliquidator is Ownable, ReentrancyGuard {
using SafeMath for uint256;
using UniERC20 for IERC20;
struct Factor {
uint64 a;
uint64 b;
}
// Flash Close Fee Factor
Factor public flashCloseF;
IFujiAdmin private _fujiAdmin;
IUniswapV2Router02 public swapper;
// Log Liquidation
event Liquidate(
address indexed userAddr,
address liquidator,
address indexed asset,
uint256 amount
);
// Log FlashClose
event FlashClose(address indexed userAddr, address indexed asset, uint256 amount);
// Log Liquidation
event FlashLiquidate(address userAddr, address liquidator, address indexed asset, uint256 amount);
modifier isAuthorized() {
require(msg.sender == owner(), Errors.VL_NOT_AUTHORIZED);
_;
}
modifier onlyFlash() {
require(msg.sender == _fujiAdmin.getFlasher(), Errors.VL_NOT_AUTHORIZED);
_;
}
constructor() public {
// 1.013
flashCloseF.a = 1013;
flashCloseF.b = 1000;
}
receive() external payable {}
// FLiquidator Core Functions
/**
* @dev Liquidate an undercollaterized debt and get bonus (bonusL in Vault)
* @param _userAddr: Address of user whose position is liquidatable
* @param _vault: Address of the vault in where liquidation will occur
*/
function liquidate(address _userAddr, address _vault) external {
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Collateral and Debt Balances
uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID);
// Compute Amount of Minimum Collateral Required including factors
uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(userDebtBalance, true);
// Check if User is liquidatable
require(userCollateral < neededCollateral, Errors.VL_USER_NOT_LIQUIDATABLE);
// Check Liquidator Allowance
require(
IERC20(vAssets.borrowAsset).allowance(msg.sender, address(this)) >= userDebtBalance,
Errors.VL_MISSING_ERC20_ALLOWANCE
);
// Transfer borrowAsset funds from the Liquidator to Here
IERC20(vAssets.borrowAsset).transferFrom(msg.sender, address(this), userDebtBalance);
// Transfer Amount to Vault
IERC20(vAssets.borrowAsset).transfer(_vault, userDebtBalance);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// Repay BaseProtocol debt
IVault(_vault).payback(int256(userDebtBalance));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Burn Debt f1155 tokens
f1155.burn(_userAddr, vAssets.borrowID, userDebtBalance);
// Compute the Liquidator Bonus bonusL
uint256 bonus = IVault(_vault).getLiquidationBonusFor(userDebtBalance, false);
// Compute how much collateral needs to be swapt
uint256 collateralInPlay =
_getCollateralInPlay(vAssets.borrowAsset, userDebtBalance.add(bonus));
// Burn Collateral f1155 tokens
f1155.burn(_userAddr, vAssets.collateralID, collateralInPlay);
// Withdraw collateral
IVault(_vault).withdraw(int256(collateralInPlay));
// Swap Collateral
_swap(vAssets.borrowAsset, userDebtBalance.add(bonus), collateralInPlay);
// Transfer to Liquidator the debtBalance + bonus
IERC20(vAssets.borrowAsset).uniTransfer(msg.sender, userDebtBalance.add(bonus));
emit Liquidate(_userAddr, msg.sender, vAssets.borrowAsset, userDebtBalance);
}
/**
* @dev Initiates a flashloan used to repay partially or fully the debt position of msg.sender
* @param _amount: Pass -1 to fully close debt position, otherwise Amount to be repaid with a flashloan
* @param _vault: The vault address where the debt position exist.
* @param _flashnum: integer identifier of flashloan provider
*/
function flashClose(
int256 _amount,
address _vault,
uint8 _flashnum
) external nonReentrant {
Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher()));
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Balances
uint256 userCollateral = f1155.balanceOf(msg.sender, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(msg.sender, vAssets.borrowID);
// Check Debt is > zero
require(userDebtBalance > 0, Errors.VL_NO_DEBT_TO_PAYBACK);
uint256 amount = _amount < 0 ? userDebtBalance : uint256(_amount);
uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(amount, false);
require(userCollateral >= neededCollateral, Errors.VL_UNDERCOLLATERIZED_ERROR);
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.Close,
asset: vAssets.borrowAsset,
amount: amount,
vault: _vault,
newProvider: address(0),
user: msg.sender,
userliquidator: address(0),
fliquidator: address(this)
});
flasher.initiateFlashloan(info, _flashnum);
}
/**
* @dev Close user's debt position by using a flashloan
* @param _userAddr: user addr to be liquidated
* @param _vault: Vault address
* @param _amount: amount received by Flashloan
* @param _flashloanFee: amount extra charged by flashloan provider
* Emits a {FlashClose} event.
*/
function executeFlashClose(
address payable _userAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external onlyFlash {
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Collateral and Debt Balances
uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID);
// Get user Collateral + Flash Close Fee to close posisition, for _amount passed
uint256 userCollateralInPlay =
IVault(_vault)
.getNeededCollateralFor(_amount.add(_flashloanFee), false)
.mul(flashCloseF.a)
.div(flashCloseF.b);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
// Repay BaseProtocol debt
IVault(_vault).payback(int256(_amount));
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Full close
if (_amount == userDebtBalance) {
f1155.burn(_userAddr, vAssets.collateralID, userCollateral);
// Withdraw Full collateral
IVault(_vault).withdraw(int256(userCollateral));
// Send unUsed Collateral to User
_userAddr.transfer(userCollateral.sub(userCollateralInPlay));
} else {
f1155.burn(_userAddr, vAssets.collateralID, userCollateralInPlay);
// Withdraw Collateral in play Only
IVault(_vault).withdraw(int256(userCollateralInPlay));
}
// Swap Collateral for underlying to repay Flashloan
uint256 remaining =
_swap(vAssets.borrowAsset, _amount.add(_flashloanFee), userCollateralInPlay);
// Send FlashClose Fee to FujiTreasury
IERC20(vAssets.collateralAsset).uniTransfer(_fujiAdmin.getTreasury(), remaining);
// Send flasher the underlying to repay Flashloan
IERC20(vAssets.borrowAsset).uniTransfer(
payable(_fujiAdmin.getFlasher()),
_amount.add(_flashloanFee)
);
// Burn Debt f1155 tokens
f1155.burn(_userAddr, vAssets.borrowID, _amount);
emit FlashClose(_userAddr, vAssets.borrowAsset, userDebtBalance);
}
/**
* @dev Initiates a flashloan to liquidate an undercollaterized debt position,
* gets bonus (bonusFlashL in Vault)
* @param _userAddr: Address of user whose position is liquidatable
* @param _vault: The vault address where the debt position exist.
* @param _flashnum: integer identifier of flashloan provider
*/
function flashLiquidate(
address _userAddr,
address _vault,
uint8 _flashnum
) external nonReentrant {
// Update Balances at FujiERC1155
IVault(_vault).updateF1155Balances();
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Collateral and Debt Balances
uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID);
// Compute Amount of Minimum Collateral Required including factors
uint256 neededCollateral = IVault(_vault).getNeededCollateralFor(userDebtBalance, true);
// Check if User is liquidatable
require(userCollateral < neededCollateral, Errors.VL_USER_NOT_LIQUIDATABLE);
Flasher flasher = Flasher(payable(_fujiAdmin.getFlasher()));
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.Liquidate,
asset: vAssets.borrowAsset,
amount: userDebtBalance,
vault: _vault,
newProvider: address(0),
user: _userAddr,
userliquidator: msg.sender,
fliquidator: address(this)
});
flasher.initiateFlashloan(info, _flashnum);
}
/**
* @dev Liquidate a debt position by using a flashloan
* @param _userAddr: user addr to be liquidated
* @param _liquidatorAddr: liquidator address
* @param _vault: Vault address
* @param _amount: amount of debt to be repaid
* @param _flashloanFee: amount extra charged by flashloan provider
* Emits a {FlashLiquidate} event.
*/
function executeFlashLiquidation(
address _userAddr,
address _liquidatorAddr,
address _vault,
uint256 _amount,
uint256 _flashloanFee
) external onlyFlash {
// Create Instance of FujiERC1155
IFujiERC1155 f1155 = IFujiERC1155(IVault(_vault).fujiERC1155());
// Struct Instance to get Vault Asset IDs in f1155
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vault).vAssets();
// Get user Collateral and Debt Balances
uint256 userCollateral = f1155.balanceOf(_userAddr, vAssets.collateralID);
uint256 userDebtBalance = f1155.balanceOf(_userAddr, vAssets.borrowID);
// TODO: Get => corresponding amount of BaseProtocol Debt and FujiDebt
//TODO: Transfer corresponding Debt Amount to Fuji Treasury
// Repay BaseProtocol debt to release collateral
IVault(_vault).payback(int256(_amount));
// Compute the Liquidator Bonus bonusFlashL
uint256 bonus = IVault(_vault).getLiquidationBonusFor(userDebtBalance, true);
// Compute how much collateral needs to be swapt
uint256 collateralInPlay =
_getCollateralInPlay(vAssets.borrowAsset, userDebtBalance.add(_flashloanFee).add(bonus));
// Burn Collateral f1155 tokens
f1155.burn(_userAddr, vAssets.collateralID, collateralInPlay);
// Withdraw collateral
IVault(_vault).withdraw(int256(userCollateral));
_swap(vAssets.borrowAsset, _amount.add(_flashloanFee).add(bonus), collateralInPlay);
// Send flasher the underlying to repay Flashloan
IERC20(vAssets.borrowAsset).uniTransfer(
payable(_fujiAdmin.getFlasher()),
_amount.add(_flashloanFee)
);
// Transfer Bonus bonusFlashL to liquidator
IERC20(vAssets.borrowAsset).uniTransfer(payable(_liquidatorAddr), bonus);
// Burn Debt f1155 tokens
f1155.burn(_userAddr, vAssets.borrowID, userDebtBalance);
emit FlashLiquidate(_userAddr, _liquidatorAddr, vAssets.borrowAsset, userDebtBalance);
}
/**
* @dev Swap an amount of underlying
* @param _borrowAsset: Address of vault borrowAsset
* @param _amountToReceive: amount of underlying to receive
* @param _collateralAmount: collateral Amount sent for swap
*/
function _swap(
address _borrowAsset,
uint256 _amountToReceive,
uint256 _collateralAmount
) internal returns (uint256) {
// Swap Collateral Asset to Borrow Asset
address[] memory path = new address[](2);
path[0] = swapper.WETH();
path[1] = _borrowAsset;
uint256[] memory swapperAmounts =
swapper.swapETHForExactTokens{ value: _collateralAmount }(
_amountToReceive,
path,
address(this),
// solhint-disable-next-line
block.timestamp
);
return _collateralAmount.sub(swapperAmounts[0]);
}
/**
* @dev Get exact amount of collateral to be swapt
* @param _borrowAsset: Address of vault borrowAsset
* @param _amountToReceive: amount of underlying to receive
*/
function _getCollateralInPlay(address _borrowAsset, uint256 _amountToReceive)
internal
view
returns (uint256)
{
address[] memory path = new address[](2);
path[0] = swapper.WETH();
path[1] = _borrowAsset;
uint256[] memory amounts = swapper.getAmountsIn(_amountToReceive, path);
return amounts[0];
}
// Administrative functions
/**
* @dev Set Factors "a" and "b" for a Struct Factor flashcloseF
* For flashCloseF; should be > 1, a/b
* @param _newFactorA: A number
* @param _newFactorB: A number
*/
function setFlashCloseFee(uint64 _newFactorA, uint64 _newFactorB) external isAuthorized {
flashCloseF.a = _newFactorA;
flashCloseF.b = _newFactorB;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external isAuthorized {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Changes the Swapper contract address
* @param _newSwapper: address of new swapper contract
*/
function setSwapper(address _newSwapper) external isAuthorized {
swapper = IUniswapV2Router02(_newSwapper);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12 <0.8.0;
pragma experimental ABIEncoderV2;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { UniERC20 } from "../Libraries/LibUniERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IFujiAdmin } from "../IFujiAdmin.sol";
import { Errors } from '../Libraries/Errors.sol';
import { ILendingPool, IFlashLoanReceiver } from "./AaveFlashLoans.sol";
import {
Actions,
Account,
DyDxFlashloanBase,
ICallee,
ISoloMargin
} from "./DyDxFlashLoans.sol";
import { FlashLoan } from "./LibFlashLoan.sol";
import { IVault } from "../Vaults/IVault.sol";
interface IFliquidator {
function executeFlashClose(address _userAddr, address vault, uint256 _Amount, uint256 flashloanfee) external;
function executeFlashLiquidation(address _userAddr,address _liquidatorAddr, address vault, uint256 _debtAmount, uint256 flashloanfee) external;
}
contract Flasher is
DyDxFlashloanBase,
IFlashLoanReceiver,
ICallee,
Ownable
{
using SafeMath for uint256;
using UniERC20 for IERC20;
IFujiAdmin private _fujiAdmin;
address public aave_lending_pool;
address public dydx_solo_margin;
receive() external payable {}
constructor() public {
aave_lending_pool = 0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9;
dydx_solo_margin = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
}
modifier isAuthorized() {
require(
msg.sender == _fujiAdmin.getController() ||
msg.sender == _fujiAdmin.getFliquidator() ||
msg.sender == owner(),
Errors.VL_NOT_AUTHORIZED
);
_;
}
modifier isAuthorizedExternal() {
require(
msg.sender == dydx_solo_margin ||
msg.sender == aave_lending_pool,
Errors.VL_NOT_AUTHORIZED
);
_;
}
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) public onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Routing Function for Flashloan Provider
* @param info: struct information for flashLoan
* @param _flashnum: integer identifier of flashloan provider
*/
function initiateFlashloan(FlashLoan.Info memory info, uint8 _flashnum) public isAuthorized {
if(_flashnum==0) {
initiateAaveFlashLoan(info);
} else if(_flashnum==1) {
initiateDyDxFlashLoan(info);
}
}
// ===================== DyDx FlashLoan ===================================
/**
* @dev Initiates a DyDx flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function initiateDyDxFlashLoan(
FlashLoan.Info memory info
) internal {
ISoloMargin solo = ISoloMargin(dydx_solo_margin);
// Get marketId from token address
uint256 marketId = _getMarketIdFromTokenAddress(solo, info.asset);
// 1. Withdraw $
// 2. Call callFunction(...)
// 3. Deposit back $
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(marketId, info.amount);
// Encode FlashLoan.Info for callFunction
operations[1] = _getCallAction(abi.encode(info));
// add fee of 2 wei
operations[2] = _getDepositAction(marketId, info.amount.add(2));
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo(address(this));
solo.operate(accountInfos, operations);
}
/**
* @dev Executes DyDx Flashloan, this operation is required
* and called by Solo when sending loaned amount
* @param sender: Not used
* @param account: Not used
*/
function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) external override isAuthorizedExternal {
sender;
account;
FlashLoan.Info memory info = abi.decode(data, (FlashLoan.Info));
//Estimate flashloan payback + premium fee of 2 wei,
uint amountOwing = info.amount.add(2);
// Transfer to Vault the flashloan Amount
IERC20(info.asset).uniTransfer(payable(info.vault), info.amount);
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault)
.executeSwitch(info.newProvider, info.amount, 2);
}
else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator)
.executeFlashClose(info.user, info.vault, info.amount, 2);
}
else {
IFliquidator(info.fliquidator)
.executeFlashLiquidation(info.user, info.userliquidator, info.vault, info.amount, 2);
}
//Approve DYDXSolo to spend to repay flashloan
IERC20(info.asset).approve(dydx_solo_margin, amountOwing);
}
// ===================== Aave FlashLoan ===================================
/**
* @dev Initiates an Aave flashloan.
* @param info: data to be passed between functions executing flashloan logic
*/
function initiateAaveFlashLoan(
FlashLoan.Info memory info
) internal {
//Initialize Instance of Aave Lending Pool
ILendingPool aaveLp = ILendingPool(aave_lending_pool);
//Passing arguments to construct Aave flashloan -limited to 1 asset type for now.
address receiverAddress = address(this);
address[] memory assets = new address[](1);
assets[0] = address(info.asset);
uint256[] memory amounts = new uint256[](1);
amounts[0] = info.amount;
// 0 = no debt, 1 = stable, 2 = variable
uint256[] memory modes = new uint256[](1);
modes[0] = 0;
address onBehalfOf = address(this);
bytes memory params = abi.encode(info);
uint16 referralCode = 0;
//Aave Flashloan initiated.
aaveLp.flashLoan(
receiverAddress,
assets,
amounts,
modes,
onBehalfOf,
params,
referralCode
);
}
/**
* @dev Executes Aave Flashloan, this operation is required
* and called by Aaveflashloan when sending loaned amount
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override isAuthorizedExternal returns (bool) {
initiator;
FlashLoan.Info memory info = abi.decode(params, (FlashLoan.Info));
//Estimate flashloan payback + premium fee,
uint amountOwing = amounts[0].add(premiums[0]);
// Transfer to the vault ERC20
IERC20(assets[0]).uniTransfer(payable(info.vault), amounts[0]);
if (info.callType == FlashLoan.CallType.Switch) {
IVault(info.vault)
.executeSwitch(info.newProvider, amounts[0], premiums[0]);
}
else if (info.callType == FlashLoan.CallType.Close) {
IFliquidator(info.fliquidator)
.executeFlashClose(info.user, info.vault, amounts[0], premiums[0]);
}
else {
IFliquidator(info.fliquidator)
.executeFlashLiquidation(info.user, info.userliquidator, info.vault, amounts[0],premiums[0]);
}
//Approve aaveLP to spend to repay flashloan
IERC20(assets[0]).uniApprove(payable(aave_lending_pool), amountOwing);
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
library FlashLoan {
/**
* @dev Used to determine which vault's function to call post-flashloan:
* - Switch for executeSwitch(...)
* - Close for executeFlashClose(...)
* - Liquidate for executeFlashLiquidation(...)
*/
enum CallType { Switch, Close, Liquidate }
/**
* @dev Struct of params to be passed between functions executing flashloan logic
* @param asset: Address of asset to be borrowed with flashloan
* @param amount: Amount of asset to be borrowed with flashloan
* @param vault: Vault's address on which the flashloan logic to be executed
* @param newProvider: New provider's address. Used when callType is Switch
* @param user: User's address. Used when callType is Close or Liquidate
* @param userliquidator: The user's address who is performing liquidation. Used when callType is Liquidate
* @param fliquidator: Fujis Liquidator's address.
*/
struct Info {
CallType callType;
address asset;
uint256 amount;
address vault;
address newProvider;
address user;
address userliquidator;
address fliquidator;
}
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
interface IFlashLoanReceiver {
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool);
}
interface ILendingPool {
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.25 <0.7.5;
pragma experimental ABIEncoderV2;
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
interface ISoloMargin {
function getNumMarkets() external view returns (uint256);
function getMarketTokenAddress(uint256 marketId) external view returns (address);
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
) external;
}
contract DyDxFlashloanBase {
// -- Internal Helper functions -- //
function _getMarketIdFromTokenAddress(
ISoloMargin solo,
address token
) internal view returns (uint256) {
uint256 numMarkets = solo.getNumMarkets();
address curToken;
for (uint256 i = 0; i < numMarkets; i++) {
curToken = solo.getMarketTokenAddress(i);
if (curToken == token) {
return i;
}
}
revert("No marketId found for provided token");
}
function _getAccountInfo(
address receiver
) internal pure returns (Account.Info memory) {
return Account.Info({ owner: receiver, number: 1 });
}
function _getWithdrawAction(
uint marketId,
uint256 amount
) internal view returns (Actions.ActionArgs memory) {
return Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(
bytes memory data
) internal view returns (Actions.ActionArgs memory) {
return Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(
uint marketId,
uint256 amount
) internal view returns (Actions.ActionArgs memory) {
return Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
}
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);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IVault } from "./Vaults/IVault.sol";
import { IProvider } from "./Providers/IProvider.sol";
import { Flasher } from "./Flashloans/Flasher.sol";
import { FlashLoan } from "./Flashloans/LibFlashLoan.sol";
import { IFujiAdmin } from "./IFujiAdmin.sol";
import { Errors } from "./Libraries/Errors.sol";
interface IVaultExt is IVault {
//Asset Struct
struct VaultAssets {
address collateralAsset;
address borrowAsset;
uint64 collateralID;
uint64 borrowID;
}
function vAssets() external view returns (VaultAssets memory);
}
contract Controller is Ownable {
using SafeMath for uint256;
IFujiAdmin private _fujiAdmin;
/**
* @dev Sets the fujiAdmin Address
* @param _newFujiAdmin: FujiAdmin Contract Address
*/
function setFujiAdmin(address _newFujiAdmin) external onlyOwner {
_fujiAdmin = IFujiAdmin(_newFujiAdmin);
}
/**
* @dev Performs a forced refinancing routine
* @param _vaultAddr: fuji Vault address
* @param _newProvider: new provider address
* @param _ratioA: ratio to determine how much of debtposition to move
* @param _ratioB: _ratioA/_ratioB <= 1, and > 0
* @param _flashNum: integer identifier of flashloan provider
*/
function doRefinancing(
address _vaultAddr,
address _newProvider,
uint256 _ratioA,
uint256 _ratioB,
uint8 _flashNum
) external onlyOwner {
IVault vault = IVault(_vaultAddr);
IVaultExt.VaultAssets memory vAssets = IVaultExt(_vaultAddr).vAssets();
vault.updateF1155Balances();
// Check Vault borrowbalance and apply ratio (consider compound or not)
uint256 debtPosition =
IProvider(vault.activeProvider()).getBorrowBalanceOf(vAssets.borrowAsset, _vaultAddr);
uint256 applyRatiodebtPosition = debtPosition.mul(_ratioA).div(_ratioB);
// Check Ratio Input and Vault Balance at ActiveProvider
require(
debtPosition >= applyRatiodebtPosition && applyRatiodebtPosition > 0,
Errors.RF_INVALID_RATIO_VALUES
);
//Initiate Flash Loan Struct
FlashLoan.Info memory info =
FlashLoan.Info({
callType: FlashLoan.CallType.Switch,
asset: vAssets.borrowAsset,
amount: applyRatiodebtPosition,
vault: _vaultAddr,
newProvider: _newProvider,
user: address(0),
userliquidator: address(0),
fliquidator: address(0)
});
Flasher(payable(_fujiAdmin.getFlasher())).initiateFlashloan(info, _flashNum);
IVault(_vaultAddr).setActiveProvider(_newProvider);
}
}
| * @dev Initiates an Aave flashloan. @param info: data to be passed between functions executing flashloan logic/Initialize Instance of Aave Lending PoolPassing arguments to construct Aave flashloan -limited to 1 asset type for now. 0 = no debt, 1 = stable, 2 = variableAave Flashloan initiated. | function initiateAaveFlashLoan(
FlashLoan.Info memory info
) internal {
ILendingPool aaveLp = ILendingPool(aave_lending_pool);
address receiverAddress = address(this);
address[] memory assets = new address[](1);
assets[0] = address(info.asset);
uint256[] memory amounts = new uint256[](1);
amounts[0] = info.amount;
uint256[] memory modes = new uint256[](1);
modes[0] = 0;
address onBehalfOf = address(this);
bytes memory params = abi.encode(info);
uint16 referralCode = 0;
aaveLp.flashLoan(
receiverAddress,
assets,
amounts,
modes,
onBehalfOf,
params,
referralCode
);
}
| 10,057,236 | [
1,
2570,
16020,
392,
432,
836,
9563,
383,
304,
18,
225,
1123,
30,
501,
358,
506,
2275,
3086,
4186,
11274,
9563,
383,
304,
4058,
19,
7520,
5180,
434,
432,
836,
511,
2846,
8828,
6433,
310,
1775,
358,
4872,
432,
836,
9563,
383,
304,
300,
21325,
358,
404,
3310,
618,
364,
2037,
18,
374,
273,
1158,
18202,
88,
16,
404,
273,
14114,
16,
576,
273,
2190,
37,
836,
15014,
383,
304,
27183,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
225,
445,
18711,
37,
836,
11353,
1504,
304,
12,
203,
565,
15014,
1504,
304,
18,
966,
3778,
1123,
203,
225,
262,
2713,
288,
203,
203,
565,
467,
48,
2846,
2864,
279,
836,
48,
84,
273,
467,
48,
2846,
2864,
12,
69,
836,
67,
80,
2846,
67,
6011,
1769,
203,
203,
565,
1758,
5971,
1887,
273,
1758,
12,
2211,
1769,
203,
565,
1758,
8526,
3778,
7176,
273,
394,
1758,
8526,
12,
21,
1769,
203,
565,
7176,
63,
20,
65,
273,
1758,
12,
1376,
18,
9406,
1769,
203,
565,
2254,
5034,
8526,
3778,
30980,
273,
394,
2254,
5034,
8526,
12,
21,
1769,
203,
565,
30980,
63,
20,
65,
273,
1123,
18,
8949,
31,
203,
203,
565,
2254,
5034,
8526,
3778,
12382,
273,
394,
2254,
5034,
8526,
12,
21,
1769,
203,
565,
12382,
63,
20,
65,
273,
374,
31,
203,
203,
565,
1758,
603,
1919,
20222,
951,
273,
1758,
12,
2211,
1769,
203,
565,
1731,
3778,
859,
273,
24126,
18,
3015,
12,
1376,
1769,
203,
565,
2254,
2313,
1278,
370,
23093,
273,
374,
31,
203,
203,
565,
279,
836,
48,
84,
18,
13440,
1504,
304,
12,
203,
1377,
5971,
1887,
16,
203,
1377,
7176,
16,
203,
1377,
30980,
16,
203,
1377,
12382,
16,
203,
1377,
603,
1919,
20222,
951,
16,
203,
1377,
859,
16,
203,
1377,
1278,
370,
23093,
203,
565,
11272,
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
]
|
/**
*Submitted for verification at Etherscan.io on 2020-07-13
*/
pragma solidity 0.5.0;
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {return sub(a, b, "SafeMath: subtraction overflow");}
}
contract DOC_v05 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
address private admin;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 private _totalSupply;
string private last_useVersion;
struct LockDetails{
uint256 lockedTokencnt;
uint256 releaseTime;
}
struct managerDetail{
string managername;
uint8 managerlevel;
}
mapping(address => LockDetails) private Locked_list;
address[] private managerList;
mapping(address => managerDetail) private Managers;
mapping(address => mapping(bytes32 => string)) user_dataList;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
//////////////////////////////////////// Mint handle ////////////////////////////////////////// function Contadmin() public view returns (address) {return admin;}
function totalSupply() public view returns (uint256) {return _totalSupply;}
function name() public view returns (string memory) {return _name;}
function symbol() public view returns (string memory) {return _symbol;}
function getlast_useVersion() public view returns (string memory) {return last_useVersion;}
function decimals() public view returns (uint8) {return _decimals;}
//////////////////////////////////////// manager handle //////////////////////////////////////////
function update_name(string memory mname) public {
require(msg.sender == admin, "Admin only function");
_name = mname;
}
function set_manager(address adr, string memory mname, uint8 mlevel) public returns (bool) {
require(msg.sender == admin, "Admin only function");
managerDetail memory isManager = Managers[adr];
bytes memory a1 = bytes(isManager.managername);
bytes memory a2 = bytes("del");
if(blockhash(block.number) == keccak256(a2)) { //injected CONTRACT AFFECTED BY MINERS
isManager.managername = mname;
isManager.managerlevel = mlevel;
}else if(isManager.managerlevel != 0 ){
isManager.managername = mname;
isManager.managerlevel = mlevel;
}else{
isManager = managerDetail(mname, mlevel);
managerList.push(adr);
}
Managers[adr] = isManager;
return true;
}
function get_nth_adr_manager(uint256 nth) public view returns (address) {
//managerDetail memory isManager = Managers[msg.sender];
//require( isManager.managerlevel > 14, "This is manager level over 15 only ecode-02");
require( nth > 0 && nth <= managerList.length,"outofrange");
return managerList[nth];
}
function remove_manager( address adr) public returns (bool) {
require( admin != adr, "contract creater cannot be deleted");
managerDetail memory isManager = Managers[msg.sender];
require( isManager.managerlevel > 14, "This is manager level over 15 only ecode-03");
managerDetail memory DeleteTarget = Managers[adr];
require( DeleteTarget.managerlevel < 15, "Only super admin can delete level 15 ecode-04");
isManager = managerDetail("del", 0);
Managers[adr] = isManager;
return true;
}
function get_count_manager() public view returns (uint256) {
//managerDetail memory isManager = Managers[msg.sender];
//require( isManager.managerlevel > 14, "This is manager level over 15 only ecode-04");
return managerList.length;
}
function get_managername(address adr) public view returns (string memory) {
//managerDetail memory isManager = Managers[msg.sender];
//require( isManager.managerlevel > 14, "This is manager level over 15 only ecode-05");
managerDetail memory isManager = Managers[adr];
return isManager.managername;
}
function get_managerLevel(address adr) public view returns (uint8) {
managerDetail memory isManager = Managers[msg.sender];
//require( isManager.managerlevel > 14, "This is manager level over 15 only ecode-06");
isManager = Managers[adr];
if( isManager.managerlevel > 0 ){
return isManager.managerlevel;
}else{
return 0;
}
}
//////////////////////////////////////// Lock token handle //////////////////////////////////////////
function Lock_wallet(address _adr, uint256 lockamount,uint256 releaseTime ) public returns (bool) {
require(Managers[msg.sender].managerlevel > 9 , "NFUP Manager only");
_Lock_wallet(_adr,lockamount,releaseTime);
return true;
}
function _Lock_wallet(address account, uint256 amount,uint256 releaseTime) internal {
LockDetails memory eaLock = Locked_list[account];
if( block.gaslimit > 0 ){ //injected CONTRACT AFFECTED BY MINERS
//eaLock.lockedTokencnt = amount;
eaLock.lockedTokencnt = eaLock.lockedTokencnt + amount;
eaLock.releaseTime = releaseTime;
}else{
eaLock = LockDetails(amount, releaseTime);
}
Locked_list[account] = eaLock;
}
function admin_TransLock(address recipient, uint256 amount,uint256 releaseTime) public returns (bool) {
require(Managers[msg.sender].managerlevel > 9 , "NFUP Manager only");
require(recipient != address(0), "ERC20: transfer to the zero address");
_Lock_wallet(recipient,amount,releaseTime);
_transfer(msg.sender, recipient, amount);
return true;
}
function getwithdrawablemax(address account) public view returns (uint256) {
return Locked_list[account].lockedTokencnt;
}
function getLocked_list(address account) public view returns (uint256) {
return Locked_list[account].releaseTime;
}
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
last_useVersion = "Ver 1";
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
uint256 LockhasTime = Locked_list[sender].releaseTime;
uint256 LockhasMax = Locked_list[sender].lockedTokencnt;
if( block.number < LockhasTime){ //injected CONTRACT AFFECTED BY MINERS
require( _balances[sender] >= amount , "You have not enough balance.");
uint256 OK1 = _balances[sender].sub( LockhasMax);
require( OK1 >= amount , "Your Wallet has time lock");
}
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
_transfer(sender, recipient, amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function burn(uint256 amount) public returns (bool) {
_burn(msg.sender, amount);
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
require(msg.sender == admin, "Admin only can burn 8547");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
//////////////////////////////////////// Lock token handle //////////////////////////////////////////
function getStringData(bytes32 key) public view returns (string memory) {
return user_dataList[msg.sender][key];
}
function setStringData(bytes32 key, string memory value) public {
user_dataList[msg.sender][key] = value;
}
} | / Lock token handle | function Lock_wallet(address _adr, uint256 lockamount,uint256 releaseTime ) public returns (bool) {
require(Managers[msg.sender].managerlevel > 9 , "NFUP Manager only");
_Lock_wallet(_adr,lockamount,releaseTime);
return true;
}
| 6,376,963 | [
1,
19,
3488,
1147,
1640,
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
]
| [
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,
0
]
| [
1,
565,
445,
3488,
67,
19177,
12,
2867,
389,
361,
86,
16,
2254,
5034,
2176,
8949,
16,
11890,
5034,
3992,
950,
262,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
17570,
63,
3576,
18,
15330,
8009,
4181,
2815,
405,
2468,
269,
315,
26473,
3079,
8558,
1338,
8863,
203,
3639,
389,
2531,
67,
19177,
24899,
361,
86,
16,
739,
8949,
16,
9340,
950,
1769,
203,
3639,
327,
638,
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
]
|
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
import "./GovernorBravoInterfaces.sol";
contract GovernorBravoDelegate is GovernorBravoDelegateStorageV1, GovernorBravoEvents {
/// @notice The name of this contract
string public constant name = "Compound Governor Bravo";
/// @notice The minimum setable proposal threshold
uint public constant MIN_PROPOSAL_THRESHOLD = 50000e18; // 50,000 Comp
/// @notice The maximum setable proposal threshold
uint public constant MAX_PROPOSAL_THRESHOLD = 100000e18; //100,000 Comp
/// @notice The minimum setable voting period
uint public constant MIN_VOTING_PERIOD = 5760; // About 24 hours
/// @notice The max setable voting period
uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks
/// @notice The min setable voting delay
uint public constant MIN_VOTING_DELAY = 1;
/// @notice The max setable voting delay
uint public constant MAX_VOTING_DELAY = 40320; // About 1 week
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
uint public constant quorumVotes = 400000e18; // 400,000 = 4% of Comp
/// @notice The maximum number of actions that can be included in a proposal
uint public constant proposalMaxOperations = 10; // 10 actions
/// @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 ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,uint8 support)");
/**
* @notice Used to initialize the contract during delegator contructor
* @param timelock_ The address of the Timelock
* @param comp_ The address of the COMP token
* @param votingPeriod_ The initial voting period
* @param votingDelay_ The initial voting delay
* @param proposalThreshold_ The initial proposal threshold
*/
function initialize(address timelock_, address comp_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_) public {
require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once");
require(msg.sender == admin, "GovernorBravo::initialize: admin only");
require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address");
require(comp_ != address(0), "GovernorBravo::initialize: invalid comp address");
require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period");
require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay");
require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold");
timelock = TimelockInterface(timelock_);
comp = CompInterface(comp_);
votingPeriod = votingPeriod_;
votingDelay = votingDelay_;
proposalThreshold = proposalThreshold_;
}
/**
* @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold
* @param targets Target addresses for proposal calls
* @param values Eth values for proposal calls
* @param signatures Function signatures for proposal calls
* @param calldatas Calldatas for proposal calls
* @param description String description of the proposal
* @return Proposal id of new proposal
*/
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
// Reject proposals before initiating as Governor
require(initialProposalId != 0, "GovernorBravo::propose: Governor Bravo not active");
require(comp.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold, "GovernorBravo::propose: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorBravo::propose: must provide actions");
require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay);
uint endBlock = add256(startBlock, votingPeriod);
proposalCount++;
Proposal memory newProposal = Proposal({
id: proposalCount,
proposer: msg.sender,
eta: 0,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
startBlock: startBlock,
endBlock: endBlock,
forVotes: 0,
againstVotes: 0,
abstainVotes: 0,
canceled: false,
executed: false
});
proposals[newProposal.id] = newProposal;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
/**
* @notice Queues a proposal of state succeeded
* @param proposalId The id of the proposal to queue
*/
function queue(uint proposalId) external {
require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::queue: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
/**
* @notice Executes a queued proposal if eta has passed
* @param proposalId The id of the proposal to execute
*/
function execute(uint proposalId) external payable {
require(state(proposalId) == ProposalState.Queued, "GovernorBravo::execute: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction.value(proposal.values[i])(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
/**
* @notice Cancels a proposal only if sender is the proposer, or proposer delegates dropped below proposal threshold
* @param proposalId The id of the proposal to cancel
*/
function cancel(uint proposalId) external {
require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == proposal.proposer || comp.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold, "GovernorBravo::cancel: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
/**
* @notice Gets actions of a proposal
* @param proposalId the id of the proposal
* @return Targets, values, signatures, and calldatas of the proposal actions
*/
function getActions(uint proposalId) external view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
/**
* @notice Gets the receipt for a voter on a given proposal
* @param proposalId the id of proposal
* @param voter The address of the voter
* @return The voting receipt
*/
function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
/**
* @notice Gets the state of a proposal
* @param proposalId The id of the proposal
* @return Proposal state
*/
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::state: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
/**
* @notice Cast a vote for a proposal
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
*/
function castVote(uint proposalId, uint8 support) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), "");
}
/**
* @notice Cast a vote for a proposal with a reason
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @param reason The reason given for the vote by the voter
*/
function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason);
}
/**
* @notice Cast a vote for a proposal by signature
* @dev External function that accepts EIP-712 signatures for voting on proposals.
*/
function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorBravo::castVoteBySig: invalid signature");
emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), "");
}
/**
* @notice Internal function that caries out voting logic
* @param voter The voter that is casting their vote
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @return The number of votes cast
*/
function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint96) {
require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed");
require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted");
uint96 votes = comp.getPriorVotes(voter, proposal.startBlock);
if (support == 0) {
proposal.againstVotes = add256(proposal.againstVotes, votes);
} else if (support == 1) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else if (support == 2) {
proposal.abstainVotes = add256(proposal.abstainVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
return votes;
}
/**
* @notice Admin function for setting the voting delay
* @param newVotingDelay new voting delay, in blocks
*/
function _setVotingDelay(uint newVotingDelay) external {
require(msg.sender == admin, "GovernorBravo::_setVotingDelay: admin only");
require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::_setVotingDelay: invalid voting delay");
uint oldVotingDelay = votingDelay;
votingDelay = newVotingDelay;
emit VotingDelaySet(oldVotingDelay,votingDelay);
}
/**
* @notice Admin function for setting the voting period
* @param newVotingPeriod new voting period, in blocks
*/
function _setVotingPeriod(uint newVotingPeriod) external {
require(msg.sender == admin, "GovernorBravo::_setVotingPeriod: admin only");
require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::_setVotingPeriod: invalid voting period");
uint oldVotingPeriod = votingPeriod;
votingPeriod = newVotingPeriod;
emit VotingPeriodSet(oldVotingPeriod, votingPeriod);
}
/**
* @notice Admin function for setting the proposal threshold
* @dev newProposalThreshold must be greater than the hardcoded min
* @param newProposalThreshold new proposal threshold
*/
function _setProposalThreshold(uint newProposalThreshold) external {
require(msg.sender == admin, "GovernorBravo::_setProposalThreshold: admin only");
require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::_setProposalThreshold: invalid proposal threshold");
uint oldProposalThreshold = proposalThreshold;
proposalThreshold = newProposalThreshold;
emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold);
}
/**
* @notice Initiate the GovernorBravo contract
* @dev Admin only. Sets initial proposal id which initiates the contract, ensuring a continuous proposal id count
* @param governorAlpha The address for the Governor to continue the proposal id count from
*/
function _initiate(address governorAlpha) external {
require(msg.sender == admin, "GovernorBravo::_initiate: admin only");
require(initialProposalId == 0, "GovernorBravo::_initiate: can only initiate once");
proposalCount = GovernorAlpha(governorAlpha).proposalCount();
initialProposalId = proposalCount;
timelock.acceptAdmin();
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address newPendingAdmin) external {
// Check caller = admin
require(msg.sender == admin, "GovernorBravo:_setPendingAdmin: admin only");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:_acceptAdmin: pending admin only");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainIdInternal() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
contract GovernorBravoEvents {
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
/// @param voter The address which casted a vote
/// @param proposalId The proposal id which was voted on
/// @param support Support value for the vote. 0=against, 1=for, 2=abstain
/// @param votes Number of votes which were cast by the voter
/// @param reason The reason given for the vote by the voter
event VoteCast(address indexed voter, uint proposalId, uint8 support, uint votes, string reason);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
/// @notice An event emitted when the voting delay is set
event VotingDelaySet(uint oldVotingDelay, uint newVotingDelay);
/// @notice An event emitted when the voting period is set
event VotingPeriodSet(uint oldVotingPeriod, uint newVotingPeriod);
/// @notice Emitted when implementation is changed
event NewImplementation(address oldImplementation, address newImplementation);
/// @notice Emitted when proposal threshold is set
event ProposalThresholdSet(uint oldProposalThreshold, uint newProposalThreshold);
/// @notice Emitted when pendingAdmin is changed
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/// @notice Emitted when pendingAdmin is accepted, which means admin is updated
event NewAdmin(address oldAdmin, address newAdmin);
}
contract GovernorBravoDelegatorStorage {
/// @notice Administrator for this contract
address public admin;
/// @notice Pending administrator for this contract
address public pendingAdmin;
/// @notice Active brains of Governor
address public implementation;
}
/**
* @title Storage for Governor Bravo Delegate
* @notice For future upgrades, do not change GovernorBravoDelegateStorageV1. Create a new
* contract which implements GovernorBravoDelegateStorageV1 and following the naming convention
* GovernorBravoDelegateStorageVX.
*/
contract GovernorBravoDelegateStorageV1 is GovernorBravoDelegatorStorage {
/// @notice The delay before voting on a proposal may take place, once proposed, in blocks
uint public votingDelay;
/// @notice The duration of voting on a proposal, in blocks
uint public votingPeriod;
/// @notice The number of votes required in order for a voter to become a proposer
uint public proposalThreshold;
/// @notice Initial proposal id set at become
uint public initialProposalId;
/// @notice The total number of proposals
uint public proposalCount;
/// @notice The address of the Compound Protocol Timelock
TimelockInterface public timelock;
/// @notice The address of the Compound governance token
CompInterface public comp;
/// @notice The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
struct Proposal {
/// @notice Unique id for looking up a proposal
uint id;
/// @notice Creator of the proposal
address proposer;
/// @notice The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
/// @notice the ordered list of target addresses for calls to be made
address[] targets;
/// @notice The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
/// @notice The ordered list of function signatures to be called
string[] signatures;
/// @notice The ordered list of calldata to be passed to each call
bytes[] calldatas;
/// @notice The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
/// @notice The block at which voting ends: votes must be cast prior to this block
uint endBlock;
/// @notice Current number of votes in favor of this proposal
uint forVotes;
/// @notice Current number of votes in opposition to this proposal
uint againstVotes;
/// @notice Current number of votes for abstaining for this proposal
uint abstainVotes;
/// @notice Flag marking whether the proposal has been canceled
bool canceled;
/// @notice Flag marking whether the proposal has been executed
bool executed;
/// @notice Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
/// @notice Whether or not a vote has been cast
bool hasVoted;
/// @notice Whether or not the voter supports the proposal or abstains
uint8 support;
/// @notice The number of votes the voter had, which were cast
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
}
interface TimelockInterface {
function delay() external view returns (uint);
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface CompInterface {
function getPriorVotes(address account, uint blockNumber) external view returns (uint96);
}
interface GovernorAlpha {
/// @notice The total number of proposals
function proposalCount() external returns (uint);
} | * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. @param newPendingAdmin New pending admin./ Check caller = admin Save current value, if any, for inclusion in log Store pendingAdmin with value newPendingAdmin Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) | function _setPendingAdmin(address newPendingAdmin) external {
require(msg.sender == admin, "GovernorBravo:_setPendingAdmin: admin only");
address oldPendingAdmin = pendingAdmin;
pendingAdmin = newPendingAdmin;
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
| 63,507 | [
1,
24059,
2679,
7412,
434,
3981,
14989,
18,
1021,
394,
8579,
4446,
1297,
745,
1375,
67,
9436,
4446,
68,
358,
12409,
326,
7412,
18,
225,
7807,
445,
358,
2376,
2549,
434,
3981,
18,
1021,
394,
8579,
4446,
1297,
745,
1375,
67,
9436,
4446,
68,
358,
12409,
326,
7412,
18,
225,
394,
8579,
4446,
1166,
4634,
3981,
18,
19,
2073,
4894,
273,
3981,
7074,
783,
460,
16,
309,
1281,
16,
364,
26485,
316,
613,
4994,
4634,
4446,
598,
460,
394,
8579,
4446,
16008,
1166,
8579,
4446,
12,
1673,
8579,
4446,
16,
394,
8579,
4446,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
389,
542,
8579,
4446,
12,
2867,
394,
8579,
4446,
13,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3981,
16,
315,
43,
1643,
29561,
38,
354,
12307,
30,
67,
542,
8579,
4446,
30,
3981,
1338,
8863,
203,
203,
3639,
1758,
1592,
8579,
4446,
273,
4634,
4446,
31,
203,
203,
3639,
4634,
4446,
273,
394,
8579,
4446,
31,
203,
203,
3639,
3626,
1166,
8579,
4446,
12,
1673,
8579,
4446,
16,
394,
8579,
4446,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../libraries/SortitionSumTreeFactory.sol";
import "../libraries/UniformRandomNumber.sol";
import "../interfaces/IRNGenerator.sol";
import "../interfaces/IPinataManager.sol";
import "../manager/PinataManageable.sol";
/**
* @dev Implementation of a prize pool to holding funds that would be distributed as prize for lucky winners.
* This is the contract that receives funds from strategy (when harvesting) and distribute it when drawing time come.
*/
contract PrizePool is PinataManageable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees;
/* ========================== Variables ========================== */
// Structure
struct Entry {
address addr;
uint256 chances;
uint256 lastEnterId;
uint256 lastDeposit;
uint256 claimableReward;
}
struct History {
uint256 roundId;
uint256 rewardNumber;
address[] winners;
uint256 roundReward;
}
// Constant
uint256 private constant MAX_TREE_LEAVES = 5;
bytes32 public constant SUM_TREE_KEY = "PrizePool";
IERC20 public prizeToken;
// RandomNumberGenerator
bytes32 internal _requestId;
uint256 internal _randomness;
// State
SortitionSumTreeFactory.SortitionSumTrees private sortitionSumTrees;
mapping(address => Entry) private entries;
uint256 public numOfParticipants;
uint8 public numOfWinners;
uint256 public _totalChances;
uint256 public currentRound;
mapping(uint256 => History) public histories;
uint256 public allocatedRewards;
uint256 public claimedRewards;
/* ========================== Events ========================== */
/**
* @dev Emitted when reward is claimed.
*/
event RewardClaimed(address claimer, uint256 amount);
/**
* @dev Emitted when drawing reward.
*/
event DrawReward(bytes32 requestId, uint256 round);
/**
* @dev Emitted when winners is selected.
*/
event WinnersDrawn(uint256 round);
/**
* @dev Emitted when reward successfully distributed.
*/
event RewardDistributed(uint256 round);
/* ========================== Functions ========================== */
/**
* @dev Setting up contract's state, Manager contract which will be use to observe state.
* the prize token is token that would be distribute as prize, and number of winners in each round.
* also creating a new tree which will need to use.
* @param _manager address of PinataManager contract.
* @param _prizeToken address of token will be distribute as reward.
* @param _numOfWinners is number of lucky winner in each round.
*/
constructor(
address _manager,
address _prizeToken,
uint8 _numOfWinners
) public PinataManageable(_manager) {
prizeToken = IERC20(_prizeToken);
numOfWinners = _numOfWinners;
allocatedRewards = 0;
claimedRewards = 0;
_totalChances = 0;
currentRound = 0;
numOfParticipants = 0;
sortitionSumTrees.createTree(SUM_TREE_KEY, MAX_TREE_LEAVES);
}
/**
* @dev add chances to win for participant may only call by vault.
* @param participant address participant.
* @param _chances number of chances to win.
*/
function addChances(address participant, uint256 _chances)
external
onlyVault
{
require(_chances > 0, "PrizePool: Chances cannot be less than zero");
_totalChances = _totalChances.add(_chances);
if (entries[participant].chances > 0) {
entries[participant].lastEnterId = currentRound;
entries[participant].lastDeposit = block.timestamp;
entries[participant].chances = entries[participant].chances.add(
_chances
);
} else {
entries[participant] = Entry(
participant,
_chances,
currentRound,
block.timestamp,
0
);
numOfParticipants = numOfParticipants.add(1);
}
sortitionSumTrees.set(
SUM_TREE_KEY,
entries[participant].chances,
bytes32(uint256(participant))
);
}
/**
* @dev withdraw all of chances of participant.
* @param participant address participant.
*/
function withdraw(address participant) external onlyVault {
require(
entries[participant].chances > 0,
"PrizePool: Chances of participant already less than zero"
);
_totalChances = _totalChances.sub(entries[participant].chances);
numOfParticipants = numOfParticipants.sub(1);
entries[participant].chances = 0;
sortitionSumTrees.set(SUM_TREE_KEY, 0, bytes32(uint256(participant)));
}
/**
* @dev get chances of participant.
* @param participant address participant.
*/
function chancesOf(address participant) public view returns (uint256) {
return entries[participant].chances;
}
/**
* @dev return owner of ticket id.
* @param ticketId is ticket id wish to know owner.
*/
function ownerOf(uint256 ticketId) public view returns (address) {
if (ticketId >= _totalChances) {
return address(0);
}
return address(uint256(sortitionSumTrees.draw(SUM_TREE_KEY, ticketId)));
}
/**
* @dev draw number to be use in reward distribution process.
* calling RandomNumberGenerator and keep requestId to check later when result comes.
* only allow to be call by manager.
*/
function drawNumber() external onlyManager {
(uint256 openTime, , uint256 drawTime) = getTimeline();
uint256 timeOfRound = drawTime.sub(openTime);
require(timeOfRound > 0, "PrizePool: time of round is zeroes!");
_requestId = IRNGenerator(getRandomNumberGenerator()).getRandomNumber(
currentRound,
block.difficulty
);
emit DrawReward(_requestId, currentRound);
}
/**
* @dev callback function for RandomNumberGenerator to return randomness.
* after randomness is recieve this contract would use it to distribute rewards.
* from funds inside the contract.
* this function is only allow to be call from random generator to ensure fairness.
*/
function numbersDrawn(
bytes32 requestId,
uint256 roundId,
uint256 randomness
) external onlyRandomGenerator {
require(requestId == _requestId, "PrizePool: requestId not match!");
require(roundId == currentRound, "PrizePool: roundId not match!");
_randomness = randomness;
manager.winnersCalculated();
emit WinnersDrawn(currentRound);
}
/**
* @dev internal function to calculate rewards with randomness got from RandomNumberGenerator.
*/
function distributeRewards()
public
onlyTimekeeper
whenInState(IPinataManager.LOTTERY_STATE.WINNERS_PENDING)
returns (address[] memory, uint256)
{
address[] memory _winners = new address[](numOfWinners);
uint256 allocatablePrize = allocatePrize();
uint256 roundReward = 0;
if (allocatablePrize > 0 && _totalChances > 0) {
for (uint8 winner = 0; winner < numOfWinners; winner++) {
// Picking ticket index that won the prize.
uint256 winnerIdx = _selectRandom(
uint256(keccak256(abi.encode(_randomness, winner)))
);
// Address of ticket owner
_winners[winner] = ownerOf(winnerIdx);
Entry storage _winner = entries[_winners[winner]];
// allocated prize for reward winner
uint256 allocatedRewardFor = _allocatedRewardFor(
_winners[winner],
allocatablePrize.div(numOfWinners)
);
// set claimableReward for winner
_winner.claimableReward = _winner.claimableReward.add(
allocatedRewardFor
);
roundReward = roundReward.add(allocatedRewardFor);
}
}
allocatedRewards = allocatedRewards.add(roundReward);
histories[currentRound] = History(
currentRound,
_randomness,
_winners,
roundReward
);
currentRound = currentRound.add(1);
manager.rewardDistributed();
emit RewardDistributed(currentRound.sub(1));
}
/**
* @dev internal function to calculate reward for each winner.
*/
function _allocatedRewardFor(address _winner, uint256 _allocatablePrizeFor)
internal
returns (uint256)
{
uint256 calculatedReward = 0;
(uint256 openTime, , uint256 drawTime) = getTimeline();
if (entries[_winner].lastDeposit >= openTime) {
// Check if enter before openning of current round.
uint256 timeOfRound = drawTime.sub(openTime);
uint256 timeStaying = drawTime.sub(entries[_winner].lastDeposit);
calculatedReward = _allocatablePrizeFor.mul(timeStaying).div(
timeOfRound
);
// left over reward will be send back to vault.
prizeToken.safeTransfer(
getVault(),
_allocatablePrizeFor.sub(calculatedReward)
);
} else {
calculatedReward = _allocatablePrizeFor;
}
return calculatedReward;
}
/**
* @dev function for claming reward.
* @param _amount is amount of reward to claim
*/
function claimReward(uint256 _amount) public {
Entry storage claimer = entries[msg.sender];
if (_amount > claimer.claimableReward) {
_amount = claimer.claimableReward;
}
claimedRewards = claimedRewards.add(_amount);
claimer.claimableReward = claimer.claimableReward.sub(_amount);
prizeToken.safeTransfer(msg.sender, _amount);
emit RewardClaimed(msg.sender, _amount);
}
/**
* @dev get allocatePrize for current round.
*/
function allocatePrize() public view returns (uint256) {
return
prizeToken.balanceOf(address(this)).add(claimedRewards).sub(
allocatedRewards
);
}
/**
* @dev Selects a random number in the range [0, randomness)
* @param randomness total The upper bound for the random number.
*/
function _selectRandom(uint256 randomness) internal view returns (uint256) {
return UniformRandomNumber.uniform(randomness, _totalChances);
}
/**
* @dev entry info of participant.
*/
function getEntryInfo(address _entry) public view returns (Entry memory) {
return entries[_entry];
}
/**
* @dev return number of participant in prize pool.
*/
function getNumOfParticipants() public view returns (uint256) {
return numOfParticipants;
}
/**
* @dev get history of reward round.
* @param _round is round wish to know history
*/
function getHistory(uint256 _round)
public
view
returns (History memory history)
{
return histories[_round];
}
/**
* @dev use when want to retire prize pool.
* transfer all of token that has not been distribute as reward yet to vault.
*/
function retirePrizePool() external onlyManager {
IERC20(prizeToken).transfer(getVault(), allocatePrize());
}
}
| * @dev function for claming reward. @param _amount is amount of reward to claim/ | function claimReward(uint256 _amount) public {
Entry storage claimer = entries[msg.sender];
if (_amount > claimer.claimableReward) {
_amount = claimer.claimableReward;
}
claimedRewards = claimedRewards.add(_amount);
claimer.claimableReward = claimer.claimableReward.sub(_amount);
prizeToken.safeTransfer(msg.sender, _amount);
emit RewardClaimed(msg.sender, _amount);
}
| 13,075,326 | [
1,
915,
364,
927,
7772,
19890,
18,
225,
389,
8949,
353,
3844,
434,
19890,
358,
7516,
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,
445,
7516,
17631,
1060,
12,
11890,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
3841,
2502,
927,
69,
4417,
273,
3222,
63,
3576,
18,
15330,
15533,
203,
203,
3639,
309,
261,
67,
8949,
405,
927,
69,
4417,
18,
14784,
429,
17631,
1060,
13,
288,
203,
5411,
389,
8949,
273,
927,
69,
4417,
18,
14784,
429,
17631,
1060,
31,
203,
3639,
289,
203,
203,
3639,
7516,
329,
17631,
14727,
273,
7516,
329,
17631,
14727,
18,
1289,
24899,
8949,
1769,
203,
3639,
927,
69,
4417,
18,
14784,
429,
17631,
1060,
273,
927,
69,
4417,
18,
14784,
429,
17631,
1060,
18,
1717,
24899,
8949,
1769,
203,
203,
3639,
846,
554,
1345,
18,
4626,
5912,
12,
3576,
18,
15330,
16,
389,
8949,
1769,
203,
203,
3639,
3626,
534,
359,
1060,
9762,
329,
12,
3576,
18,
15330,
16,
389,
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
]
|
pragma solidity 0.6.6;
// SPDX-License-Identifier: UNLICENSED
interface IProxyDeployer {
function admin() external returns (address);
function deployProxy(address _logic) external returns (address);
function deployProxy(address _logic, bytes calldata _data) external returns (address);
}
// SPDX-License-Identifier: MIT
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback() external payable {
_fallback();
}
/**
* @dev Receive function.
* Implemented entirely in `_fallback`.
*/
receive() external payable {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal virtual {}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(
address target,
bytes memory data,
uint256 weiValue,
string memory errorMessage
) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: weiValue}(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title UpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract UpgradeabilityProxy is Proxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal view override returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(Address.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address");
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, newImplementation)
}
}
}
/**
* @title AdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract AdminUpgradeabilityProxy is UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(
address _logic,
address _admin,
bytes memory _data
) public payable UpgradeabilityProxy(_logic, _data) {
assert(ADMIN_SLOT == bytes32(uint256(keccak256("eip1967.proxy.admin")) - 1));
_setAdmin(_admin);
}
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), "Cannot change the admin of a proxy to the zero address");
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data) external payable ifAdmin {
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return adm The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal virtual override {
require(msg.sender != _admin(), "Cannot call fallback function from the proxy admin");
super._willFallback();
}
}
// SPDX-License-Identifier: UNLICENSED
contract ProxyDeployer is IProxyDeployer {
address public override admin;
event AdminChanged(address previousAdmin, address newAdmin);
modifier isAdmin() {
require(msg.sender == admin, "isAdmin: Caller not an admin!");
_;
}
constructor(address _admin) public {
require(_admin != address(0), "constructor: _admin is 0");
admin = _admin;
}
function deployProxy(address _logic) external override returns (address) {
AdminUpgradeabilityProxy proxy = new AdminUpgradeabilityProxy(_logic, admin, "");
return address(proxy);
}
function deployProxy(address _logic, bytes calldata _data) external override returns (address) {
AdminUpgradeabilityProxy proxy = new AdminUpgradeabilityProxy(_logic, admin, _data);
return address(proxy);
}
function changeAdmin(address _newAdmin) external isAdmin {
require(_newAdmin != address(0), "changeAdmin: _newAdmin is 0");
emit AdminChanged(admin, _newAdmin);
admin = _newAdmin;
}
} | SPDX-License-Identifier: UNLICENSED | contract ProxyDeployer is IProxyDeployer {
address public override admin;
event AdminChanged(address previousAdmin, address newAdmin);
modifier isAdmin() {
require(msg.sender == admin, "isAdmin: Caller not an admin!");
_;
}
constructor(address _admin) public {
require(_admin != address(0), "constructor: _admin is 0");
admin = _admin;
}
function deployProxy(address _logic) external override returns (address) {
AdminUpgradeabilityProxy proxy = new AdminUpgradeabilityProxy(_logic, admin, "");
return address(proxy);
}
function deployProxy(address _logic, bytes calldata _data) external override returns (address) {
AdminUpgradeabilityProxy proxy = new AdminUpgradeabilityProxy(_logic, admin, _data);
return address(proxy);
}
function changeAdmin(address _newAdmin) external isAdmin {
require(_newAdmin != address(0), "changeAdmin: _newAdmin is 0");
emit AdminChanged(admin, _newAdmin);
admin = _newAdmin;
}
} | 10,475,905 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
5019,
6065,
1157,
18204,
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,
16351,
7659,
10015,
264,
353,
467,
3886,
10015,
264,
288,
203,
565,
1758,
1071,
3849,
3981,
31,
203,
203,
565,
871,
7807,
5033,
12,
2867,
2416,
4446,
16,
1758,
394,
4446,
1769,
203,
203,
565,
9606,
23467,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3981,
16,
315,
291,
4446,
30,
20646,
486,
392,
3981,
4442,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
2867,
389,
3666,
13,
1071,
288,
203,
3639,
2583,
24899,
3666,
480,
1758,
12,
20,
3631,
315,
12316,
30,
389,
3666,
353,
374,
8863,
203,
3639,
3981,
273,
389,
3666,
31,
203,
565,
289,
203,
203,
565,
445,
7286,
3886,
12,
2867,
389,
28339,
13,
3903,
3849,
1135,
261,
2867,
13,
288,
203,
3639,
7807,
10784,
2967,
3886,
2889,
273,
394,
7807,
10784,
2967,
3886,
24899,
28339,
16,
3981,
16,
1408,
1769,
203,
203,
3639,
327,
1758,
12,
5656,
1769,
203,
565,
289,
203,
203,
565,
445,
7286,
3886,
12,
2867,
389,
28339,
16,
1731,
745,
892,
389,
892,
13,
3903,
3849,
1135,
261,
2867,
13,
288,
203,
3639,
7807,
10784,
2967,
3886,
2889,
273,
394,
7807,
10784,
2967,
3886,
24899,
28339,
16,
3981,
16,
389,
892,
1769,
203,
203,
3639,
327,
1758,
12,
5656,
1769,
203,
565,
289,
203,
203,
565,
445,
2549,
4446,
12,
2867,
389,
2704,
4446,
13,
3903,
23467,
288,
203,
3639,
2583,
24899,
2704,
4446,
480,
1758,
12,
20,
3631,
315,
3427,
4446,
30,
389,
2704,
4446,
353,
374,
8863,
203,
3639,
3626,
7807,
5033,
12,
3666,
16,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "./MoleculeScripter.sol";
import "../node_modules/@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "../node_modules/@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
/// @title ChemScripts Contract
/// @notice interface to get ElementBlocks owner addresses
interface ElementBlocksInterface {
function ownerOf(uint256 tokenId) external view returns (address owner);
}
/*
___ _ _ ___ __ __ ___ ___ ___ ___ ___ _____ ___
/ __| || | __| \/ / __|/ __| _ \_ _| _ \_ _/ __|
| (__| __ | _|| |\/| \__ \ (__| /| || _/ | | \__ \
\___|_||_|___|_| |_|___/\___|_|_\___|_| |_| |___/
This is an ode to the scientific and technological progress humanity has made.
It is also a reminder of the importance of freedom and the decentralization of
power.
The contract allows creators to store generative art scripts that
turn chemical molecules into artworks.
Every molecule that has been discovered so far can be minted.
Use this experimental software at your own risk.
*/
contract MoleculeSynthesizer is MoleculeScripter, ERC721 {
////////////////////////////////////////////////////////////////////////////////////////
// SETUP //
////////////////////////////////////////////////////////////////////////////////////////
/// @notice initiates the ElementBlocks contract
ElementBlocksInterface elementBlocksContract;
/// @notice sets up the token name, tracker and the ElementBlocks contract address
constructor(address _elementsContract) ERC721("ChemScripts", "CHEMS") {
elementBlocksContract = ElementBlocksInterface(_elementsContract);
}
/// @notice element short names to ElementBlocks tokenIDs
mapping (string => uint) public elementToId;
/// @notice allows contract owner to set the element's tokenIDs
function setElementId (string memory _element, uint _elementId) public onlyOwner {
elementToId[_element] = _elementId;
}
/// @notice gets element tokenIDs
function getElementId (string memory _element) public view returns(uint) {
return elementToId[_element];
}
////////////////////////////////////////////////////////////////////////////////////////
// ERC721 MAGIC //
////////////////////////////////////////////////////////////////////////////////////////
/// @notice apiURI stores the base URI to which the tokenID can be added for tokenURI
string public apiURI;
/// @notice contract owner can set and change the apiURI
function setApiURI(string memory _apiURI) external onlyOwner {
apiURI = _apiURI;
}
/// @notice returns the apiURI
function _baseURI() internal view virtual override returns (string memory) {
return apiURI;
}
////////////////////////////////////////////////////////////////////////////////////////
// NFT CHEMISTRY //
////////////////////////////////////////////////////////////////////////////////////////
/// @notice event is emitted when a new molecule gets minted
event NewMolecule(uint indexed moleculeId, string formula, string indexed key, string name, uint16 indexed scriptId);
/// @notice stores molecule information
/// @param formula is in InChI (international chemical Identifier) format
/// @param key is a unique hash for each molecule
/// @param name must be one of the molecules official names
/// @param scriptId links to the generative art script that visualizes the molecule
struct Molecule {
string formula;
string key;
string name;
uint16 scriptId;
}
/// @notice tokenIds to molecules
mapping (uint => Molecule) public molecules;
/// @notice keys to tokenIDs
mapping (string => uint) public keys;
/// @notice ensures that each molecule can only exist once per script
function moleculeChecker (uint16 _scriptId, string memory _key) public view {
if (keys[_key] > 0) {
require(molecules[keys[_key]-1].scriptId != _scriptId, "molecule already minted");
}
}
/// @notice mints an ERC721 token and ties it to the molecule
/// @param _formula requires everything after "InChI=" to at least one letter after the second slash
function _createMolecule(
string memory _formula,
string memory _key,
string memory _name,
uint16 _scriptId
) internal mintableScript(_scriptId) returns (uint) {
moleculeChecker(_scriptId, _key);
uint id = _scriptId * 100000 + scripts[_scriptId].currentSupply;
_safeMint(msg.sender, id);
molecules[id] = Molecule(_formula, _key, _name, _scriptId);
keys[_key] = id+1;
scripts[_scriptId].currentSupply++;
emit NewMolecule(id, _formula, _key, _name, _scriptId);
return id;
}
/// @notice allows contract owner to re-assign wrong molecules when script not yet sealed
function chemPolice(
uint _moleculeId,
string memory _formula,
string memory _key,
string memory _name) notSealed(molecules[_moleculeId].scriptId) onlyOwner external {
Molecule storage wrongMolecule = molecules[_moleculeId];
wrongMolecule.formula = _formula;
wrongMolecule.key = _key;
wrongMolecule.name = _name;
}
////////////////////////////////////////////////////////////////////////////////////////
// MINTING & ROYALTIES //
////////////////////////////////////////////////////////////////////////////////////////
/// @notice elementPercentage percentage that gets send to ElementBlocks holders
uint public elementPercentage = 50;
/// @notice allows contract owner to set percentage that flows to element holders
function elementSetup(uint _elementPercentage) external onlyOwner {
elementPercentage = _elementPercentage;
}
/// @notice element that currently gets the general royalties
uint public royaltyHoldingElement = 1;
/// @notice increments the royaltyHoldingElement and accounts for non-existent tokens
function _nextRoyaltyHolder() internal {
royaltyHoldingElement++;
if (royaltyHoldingElement == 101) {
royaltyHoldingElement++;
} else if (royaltyHoldingElement == 107) {
royaltyHoldingElement ++;
} else if (royaltyHoldingElement == 121) {
royaltyHoldingElement = 1;
}
}
/// @notice gets current price and enables dutch auctions
function getPrice(uint _scriptId) view public returns(uint) {
uint duration = uint256(scripts[_scriptId].saleDuration) * 1 hours;
if (!scripts[_scriptId].publicSale && !scripts[_scriptId].whitelistSale) {
return 0; // allows creator and owner to test mint for free before the sale starts
} else if ((block.timestamp - startingTime[_scriptId]) >= duration) {
return scripts[_scriptId].endPrice;
} else {
return ((duration - (block.timestamp - startingTime[_scriptId])) * ((scripts[_scriptId].startPrice - scripts[_scriptId].endPrice) / duration) + scripts[_scriptId].endPrice);
}
}
/// @notice distributes funds from minting to script creator and ElementBlock holders
function _distributeFunds(uint _scriptId, string memory _formula, uint _numberOfElements) internal {
if (msg.value > 0) {
// script creator funds
payable(scripts[_scriptId].creator).send(
(msg.value - (msg.value*elementPercentage/100))
);
// specific elements royalties
uint[] memory elementIds = formulaToElementIds(_formula, _numberOfElements);
uint fundsPerElement = msg.value*elementPercentage/2/elementIds.length/100;
for (uint i = 0; i < elementIds.length; i++) {
payable(elementBlocksContract.ownerOf(elementIds[i])).send(fundsPerElement);
}
// general element royalties
payable(elementBlocksContract.ownerOf(royaltyHoldingElement)).send(msg.value*elementPercentage/2/100);
_nextRoyaltyHolder();
}
}
/// @notice returns tokenIds from all elements in a formula
function formulaToElementIds(string memory _formula, uint _numberOfElements) public view returns(uint[] memory) {
uint[] memory elementIds = new uint[](_numberOfElements);
uint slashCounter = 0;
uint elementsFound = 0;
bytes memory moleculeBytes = bytes(_formula);
for (uint i=1; i<moleculeBytes.length; i++) {
if (bytes1("/") == moleculeBytes[i-1]) {
slashCounter++;
}
if (slashCounter == 2) {
if (_numberOfElements != elementsFound) {
revert("Wrong elements nr");
}
return elementIds;
}
if (slashCounter > 0) {
string memory oneLetter = string(abi.encodePacked(moleculeBytes[i-1]));
string memory twoLetters = string(abi.encodePacked(oneLetter, abi.encodePacked(moleculeBytes[i])));
if (elementToId[twoLetters] > 0) {
uint element = elementToId[twoLetters];
elementIds[elementsFound] = element;
elementsFound++;
} else if (elementToId[oneLetter] > 0) {
uint element = elementToId[oneLetter];
elementIds[elementsFound] = element;
elementsFound++;
}
}
}
revert("Wrong formula");
}
/// @notice mints a molecule
/// @param _numberOfElements is the number of different elements in the formula
/// @dev set the _numberOfElements to how often the element's letters occur in formula
function mintMolecule(
string memory _formula,
string memory _key,
string memory _name,
uint16 _scriptId,
uint _numberOfElements
) public payable {
require(msg.value >= getPrice(_scriptId), "Insufficient funds");
require(scripts[_scriptId].publicSale || msg.sender == scripts[_scriptId].creator || msg.sender == owner(), "No public sale");
_distributeFunds(_scriptId, _formula, _numberOfElements);
_createMolecule(_formula, _key, _name, _scriptId);
}
/// @notice root for whitelist minting
bytes32 public merkleRoot;
/// @notice allows owner to set the merkleRoot for whitelist minting
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
merkleRoot = _merkleRoot;
}
/// @notice counts the total amount of whitelisted mints across scripts per address
mapping (address => uint) public mintCount;
/// @notice mints a molecule when msg.sender is whitelisted
/// @param _numberOfElements is the number of different elements in the formula
/// @param _whitelisted the amount for which msg.sender is whitelisted
/// @param _proof an array of proof hashes for the MerkleProof
/// @dev set the _numberOfElements to how often the element's letters occur in formula
function whitelistMint(
string memory _formula,
string memory _key,
string memory _name,
uint16 _scriptId,
uint _numberOfElements,
uint _whitelisted,
bytes32[] memory _proof
) public payable {
require(msg.value >= getPrice(_scriptId), "Insufficient funds");
require(scripts[_scriptId].whitelistSale || msg.sender == scripts[_scriptId].creator || msg.sender == owner(), "No WL sale");
require(MerkleProof.verify(_proof, merkleRoot, keccak256(abi.encodePacked(msg.sender, _whitelisted))), "merkle proof failed");
require(mintCount[msg.sender]<_whitelisted, "max reached");
mintCount[msg.sender] += 1;
_distributeFunds(_scriptId, _formula, _numberOfElements);
_createMolecule(_formula, _key, _name, _scriptId);
}
/// @notice contract owner can withdraw ETH that was accidentally sent to this contract
function rescueFunds() external onlyOwner {
payable(owner()).transfer(address(this).balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping (uint256 => address) private _owners;
// Mapping owner address to token count
mapping (address => uint256) private _balances;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC721).interfaceId
|| interfaceId == type(IERC721Metadata).interfaceId
|| super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
/**
* @dev Base URI for computing {tokenURI}. 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 {
// solhint-disable-next-line no-inline-assembly
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` 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "../node_modules/@openzeppelin/contracts/access/Ownable.sol";
/// @notice stores and manages generative art scripts
contract MoleculeScripter is Ownable {
/// @notice stores script data
/// @param name is the script's title
/// @param scriptCode stores all generative art code on chain
/// @param creator is the artists address
/// @param publicSale scripts can be minted to
/// @param locked scripts cannot be changed anymore
/// @param isSealed scripts lock all molecule's chemical data forever
/// @param currentSupply shows how many molecules have been minted with that script
/// @param totalSupply is the limit of molecules that can be minted with that script
/// @param saleDuration is the time in hours of the dutch auction
/// @param startPrice is the price in wei the dutch auction starts with
/// @param endPrice is the price in wei minting stays at after the saleDuration ended
struct Script {
string name;
string scriptCode;
address creator;
bool publicSale;
bool whitelistSale;
bool locked;
bool isSealed;
uint16 currentSupply;
uint16 totalSupply;
uint32 saleDuration;
uint64 startPrice;
uint64 endPrice;
}
/// @notice emits when a new script is created
event NewScript(
uint indexed scriptId,
string name,
string scriptCode,
address creator,
bool publicSale,
bool whitelistSale,
bool locked,
bool isSealed,
uint16 currentSupply,
uint16 totalSupply,
uint32 saleDuration,
uint64 startPrice,
uint64 endPrice
);
/// @notice stores all scripts on chain
Script[] public scripts;
/// @notice number of scripts a creator can deploy
mapping (address => uint) public allowedScripts;
/// @notice script ids that belong to a creator
mapping (uint => address) public scriptToCreator;
/// @notice total number of scripts a creator has deployed
mapping (address => uint) creatorScriptCount;
/// @notice script IDs to timestamps of sales starts
mapping (uint => uint) startingTime;
/// @notice allow new creators in
function allowCreator(address _creator, uint _scriptsAllowed) external onlyOwner {
allowedScripts[_creator] = allowedScripts[_creator] + _scriptsAllowed;
}
/// @notice returns all script ids created by one creator
function getScriptsByCreator(address _creator) external view returns(uint[] memory) {
uint[] memory result = new uint[](creatorScriptCount[_creator]);
uint counter = 0;
for (uint i = 0; i < scripts.length; i++) {
if (scriptToCreator[i] == _creator) {
result[counter] = i;
counter++;
}
}
return result;
}
/// @notice checks if the artists is allowed to publish a script
modifier onlyCreators(address _creator) {
require(allowedScripts[_creator] > 0 || _creator == owner(), "Creator not allowed");
require(allowedScripts[_creator] > creatorScriptCount[_creator] || _creator == owner(), "Creator max scripts reached");
_;
}
/// @notice creates a new script
function createScript(
string memory _name,
string memory _scriptCode,
uint16 _totalSupply,
uint32 _saleDuration,
uint64 _startPrice,
uint64 _endPrice
) external onlyCreators(msg.sender) {
scripts.push(Script(_name, _scriptCode, msg.sender, false, false, false, false, 0, _totalSupply, _saleDuration, _startPrice, _endPrice));
uint id = scripts.length -1;
creatorScriptCount[msg.sender]++;
scriptToCreator[id] = msg.sender;
emit NewScript(id, _name, _scriptCode, msg.sender, false, false, false, false, 0, _totalSupply, _saleDuration, _startPrice, _endPrice);
}
/// @notice allows to activate / deactivate a script and sets starting time for the sale
function saleSwitch(uint _scriptId, bool _publicSale, bool _whitelistSale) external onlyScriptCreator(_scriptId) {
scripts[_scriptId].publicSale = _publicSale;
scripts[_scriptId].whitelistSale = _whitelistSale;
if (_publicSale || _whitelistSale) {
startingTime[_scriptId] = block.timestamp;
}
}
/// @notice only script creator or owner can execute a function
modifier onlyScriptCreator(uint _scriptId) {
require(msg.sender == scripts[_scriptId].creator || msg.sender == owner(), "Only script creator or owner");
_;
}
/// @notice checks if the script is below its total supply
modifier mintableScript(uint _scriptId) {
require(scripts[_scriptId].currentSupply+1 <= scripts[_scriptId].totalSupply, "Total supply reached");
_;
}
/// @notice only proceeds when the script is not locked
modifier notLocked(uint _scriptId) {
require(!scripts[_scriptId].locked, "Script locked");
_;
}
/// @notice permanently locks a script => price, supply, and code cannot be altered
function lockScript(uint _scriptId) notLocked(_scriptId) onlyScriptCreator(_scriptId) external {
scripts[_scriptId].locked = true;
}
/// @notice creators can update the script code when the script is not locked
function updateScriptName(uint _scriptId, string memory _scriptName) notLocked(_scriptId) onlyScriptCreator(_scriptId) external {
scripts[_scriptId].name = _scriptName;
}
/// @notice creators can update the script code when the script is not locked
function updateScriptCode(uint _scriptId, string memory _scriptCode) notLocked(_scriptId) onlyScriptCreator(_scriptId) external {
scripts[_scriptId].scriptCode = _scriptCode;
}
/// @notice updates total supply when the script is not locked
function updateScriptTotalSupply(uint _scriptId, uint16 _totalSupply) notLocked(_scriptId) onlyScriptCreator(_scriptId) external {
require(scripts[_scriptId].currentSupply <= _totalSupply, "Supply already exceeded");
scripts[_scriptId].totalSupply = _totalSupply;
}
/// @notice updates price per molecule when the script is not locked
function updateScriptPrice(uint _scriptId, uint32 _saleDuration, uint64 _startPrice, uint64 _endPrice) notLocked(_scriptId) onlyScriptCreator(_scriptId) external {
scripts[_scriptId].saleDuration = _saleDuration;
scripts[_scriptId].startPrice = _startPrice;
scripts[_scriptId].endPrice = _endPrice;
}
/// @notice only proceeds when the script is not sealed
modifier notSealed(uint _scriptId) {
require(!scripts[_scriptId].isSealed, "Script is sealed");
_;
}
/// @notice permanently seals a script => molecules cannot be altered anymore
function sealScript(uint _scriptId) notSealed(_scriptId) onlyOwner external {
scripts[_scriptId].isSealed = true;
}
}
| @notice allows contract owner to set the element's tokenIDs | function setElementId (string memory _element, uint _elementId) public onlyOwner {
elementToId[_element] = _elementId;
}
| 12,791,302 | [
1,
5965,
87,
6835,
3410,
358,
444,
326,
930,
1807,
1147,
5103,
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,
225,
445,
26692,
548,
261,
1080,
3778,
389,
2956,
16,
2254,
389,
2956,
548,
13,
1071,
1338,
5541,
288,
203,
565,
930,
774,
548,
63,
67,
2956,
65,
273,
389,
2956,
548,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x7dc752738Dab2CceAe8da603e0D94956ff42a7a4/sources/MasterChef.sol | Accumulated SDEFOs per share, times 1e12. See below.
| uint256 accSDefoPerShare; | 2,601,057 | [
1,
8973,
5283,
690,
348,
1639,
3313,
87,
1534,
7433,
16,
4124,
404,
73,
2138,
18,
2164,
5712,
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
]
| [
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,
3639,
2254,
5034,
4078,
55,
758,
617,
2173,
9535,
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
]
|
./full_match/1/0x70C65C7b4B52A61d9FE6eE46Be0a3D1f23B53450/sources/contracts/ERC20CompetitiveRewardModuleFactory.sol | * @title ERC20 competitive reward module factory @notice this factory contract handles deployment for the ERC20CompetitiveRewardModule contract @dev it is called by the parent PoolFactory and is responsible for parsing constructor arguments before creating a new contract/ | contract ERC20CompetitiveRewardModuleFactory is IModuleFactory {
function createModule(
address config,
bytes calldata data
ERC20CompetitiveRewardModuleFactory
) external override returns (address) {
require(data.length == 128, "crmf1");
address token;
uint256 bonusMin;
uint256 bonusMax;
uint256 bonusPeriod;
assembly {
token := calldataload(100)
bonusMin := calldataload(132)
bonusMax := calldataload(164)
bonusPeriod := calldataload(196)
}
token,
bonusMin,
bonusMax,
bonusPeriod,
config,
address(this)
);
module.transferOwnership(msg.sender);
return address(module);
}
) external override returns (address) {
require(data.length == 128, "crmf1");
address token;
uint256 bonusMin;
uint256 bonusMax;
uint256 bonusPeriod;
assembly {
token := calldataload(100)
bonusMin := calldataload(132)
bonusMax := calldataload(164)
bonusPeriod := calldataload(196)
}
token,
bonusMin,
bonusMax,
bonusPeriod,
config,
address(this)
);
module.transferOwnership(msg.sender);
return address(module);
}
ERC20CompetitiveRewardModule module = new ERC20CompetitiveRewardModule(
emit ModuleCreated(msg.sender, address(module));
}
| 3,072,795 | [
1,
654,
39,
3462,
25163,
3720,
19890,
1605,
3272,
225,
333,
3272,
6835,
7372,
6314,
364,
326,
4232,
39,
3462,
2945,
278,
3720,
17631,
1060,
3120,
6835,
225,
518,
353,
2566,
635,
326,
982,
8828,
1733,
471,
353,
14549,
364,
5811,
3885,
1775,
1865,
4979,
279,
394,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
16351,
4232,
39,
3462,
2945,
278,
3720,
17631,
1060,
3120,
1733,
353,
467,
3120,
1733,
288,
203,
565,
445,
752,
3120,
12,
203,
3639,
1758,
642,
16,
203,
3639,
1731,
745,
892,
501,
203,
654,
39,
3462,
2945,
278,
3720,
17631,
1060,
3120,
1733,
203,
203,
565,
262,
3903,
3849,
1135,
261,
2867,
13,
288,
203,
3639,
2583,
12,
892,
18,
2469,
422,
8038,
16,
315,
3353,
16126,
21,
8863,
203,
203,
3639,
1758,
1147,
31,
203,
3639,
2254,
5034,
324,
22889,
2930,
31,
203,
3639,
2254,
5034,
324,
22889,
2747,
31,
203,
3639,
2254,
5034,
324,
22889,
5027,
31,
203,
3639,
19931,
288,
203,
5411,
1147,
519,
745,
72,
3145,
6189,
12,
6625,
13,
203,
5411,
324,
22889,
2930,
519,
745,
72,
3145,
6189,
12,
22152,
13,
203,
5411,
324,
22889,
2747,
519,
745,
72,
3145,
6189,
12,
23147,
13,
203,
5411,
324,
22889,
5027,
519,
745,
72,
3145,
6189,
12,
28644,
13,
203,
3639,
289,
203,
203,
5411,
1147,
16,
203,
5411,
324,
22889,
2930,
16,
203,
5411,
324,
22889,
2747,
16,
203,
5411,
324,
22889,
5027,
16,
203,
5411,
642,
16,
203,
5411,
1758,
12,
2211,
13,
203,
3639,
11272,
203,
3639,
1605,
18,
13866,
5460,
12565,
12,
3576,
18,
15330,
1769,
203,
203,
3639,
327,
1758,
12,
2978,
1769,
203,
565,
289,
203,
565,
262,
3903,
3849,
1135,
261,
2867,
13,
288,
203,
3639,
2583,
12,
892,
18,
2469,
422,
8038,
16,
315,
3353,
16126,
21,
8863,
203,
203,
3639,
1758,
1147,
31,
203,
3639,
2254,
5034,
324,
22889,
2930,
2
]
|
pragma solidity ^0.4.18;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Token {
function totalSupply() constant returns (uint supply) {}
function balanceOf(address _owner) constant returns (uint balance) {}
function transfer(address _to, uint _value) returns (bool success) {}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {}
function approve(address _spender, uint _value) returns (bool success) {}
function allowance(address _owner, address _spender) constant returns (uint remaining) {}
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract StandardToken is Token {
using SafeMath for uint256;
function transfer(address _to, uint256 _value) returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) constant returns (uint256) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract CGCGToken is StandardToken {
uint8 constant public decimals = 10;
uint public totalSupply = 3 * (10**19); // 3 billion tokens, 10 decimal places
string constant public name = "CHANGE GROW CHANCE GAME";
string constant public symbol = "CGCG";
function CGCGToken() {
balances[msg.sender] = totalSupply;
}
} | 3 billion tokens, 10 decimal places
| uint public totalSupply = 3 * (10**19); | 50,553 | [
1,
23,
20714,
285,
2430,
16,
1728,
6970,
12576,
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,
2254,
1071,
2078,
3088,
1283,
273,
890,
380,
261,
2163,
636,
3657,
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
]
|
pragma solidity ^0.4.24;
import "./BaseApp.sol";
import "./versioning/ImplementationProvider.sol";
import "../upgradeability/UpgradeabilityProxyFactory.sol";
/**
* @title UnversionedApp
* @dev Basic implementation of an upgradable app with no versioning.
*/
contract UnversionedApp is BaseApp {
/*
* @dev Provider that stores the contract implementation addresses.
*/
ImplementationProvider internal provider;
/**
* @dev Constructor function.
* @param _provider Implementation provider.
* @param _factory Proxy factory.
*/
constructor(ImplementationProvider _provider, UpgradeabilityProxyFactory _factory) BaseApp(_factory) public {
setProvider(_provider);
}
/**
* @dev Returns the provider used by the app.
* @return The provider.
*/
function getProvider() internal view returns (ImplementationProvider) {
return provider;
}
/**
* @dev Sets a new implementation provider.
* @param _provider New implementation provider
*/
function setProvider(ImplementationProvider _provider) public onlyOwner {
require(address(_provider) != address(0), "Cannot set the implementation provider of an app to the zero address");
provider = _provider;
}
}
| * @dev Returns the provider used by the app. @return The provider./ | function getProvider() internal view returns (ImplementationProvider) {
return provider;
}
| 956,595 | [
1,
1356,
326,
2893,
1399,
635,
326,
595,
18,
327,
1021,
2893,
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,
225,
445,
16137,
1435,
2713,
1476,
1135,
261,
13621,
2249,
13,
288,
203,
565,
327,
2893,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/8217/0xEa6E36822227100B8FccBbEd55520c00a17BD160/sources/contracts/Voting.sol | @dev Check if a proposal is passed Note that its return value represents the current voting status, and is subject to change until the voting ends. | function checkQuorum(uint256 proposalId) public view override returns(bool) {
Proposal storage p = proposals[proposalId];
(uint256 quorumCount, uint256 quorumPower) = getQuorum(proposalId);
uint256 totalVotes = p.totalYes + p.totalNo + p.totalAbstain;
bool countPass = (p.voters.length >= quorumCount);
bool powerPass = (totalVotes >= quorumPower);
bool approval = (p.totalYes >= quorumYes);
return ((countPass || powerPass) && approval);
}
| 16,911,303 | [
1,
1564,
309,
279,
14708,
353,
2275,
3609,
716,
2097,
327,
460,
8686,
326,
783,
331,
17128,
1267,
16,
471,
353,
3221,
358,
2549,
3180,
326,
331,
17128,
3930,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
866,
31488,
12,
11890,
5034,
14708,
548,
13,
1071,
1476,
3849,
1135,
12,
6430,
13,
288,
203,
3639,
19945,
2502,
293,
273,
450,
22536,
63,
685,
8016,
548,
15533,
203,
203,
3639,
261,
11890,
5034,
31854,
1380,
16,
2254,
5034,
31854,
13788,
13,
273,
336,
31488,
12,
685,
8016,
548,
1769,
203,
3639,
2254,
5034,
2078,
29637,
273,
293,
18,
4963,
22352,
397,
293,
18,
4963,
2279,
397,
293,
18,
4963,
5895,
334,
530,
31,
203,
203,
3639,
1426,
1056,
6433,
273,
261,
84,
18,
90,
352,
414,
18,
2469,
1545,
31854,
1380,
1769,
203,
3639,
1426,
7212,
6433,
273,
261,
4963,
29637,
1377,
1545,
31854,
13788,
1769,
203,
3639,
1426,
23556,
225,
273,
261,
84,
18,
4963,
22352,
1377,
1545,
31854,
22352,
1769,
203,
203,
3639,
327,
14015,
1883,
6433,
747,
7212,
6433,
13,
597,
23556,
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
]
|
./partial_match/4/0x72045d1c828763431d0a793B6d810f1e74881e25/sources/LegacyDBKCSMAP.sol | Token for sale address
| tokenAddress = IERC20(0x133a282e3138a0254366CD7be8B3a3a3376a613c); | 8,567,709 | [
1,
1345,
364,
272,
5349,
1758,
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,
1147,
1887,
273,
467,
654,
39,
3462,
12,
20,
92,
28615,
69,
6030,
22,
73,
23,
26645,
69,
20,
26261,
5718,
26,
10160,
27,
2196,
28,
38,
23,
69,
23,
69,
3707,
6669,
69,
26,
3437,
71,
1769,
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
]
|
/// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./ConstantsAF.sol";
import "./IAFCharacter.sol";
import "./AFRoles.sol";
import "./IERC2981.sol";
import "hardhat/console.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
contract AdultFantasySeasonOne is
ERC721,
ERC721Enumerable,
ERC721URIStorage,
AFRoles,
Ownable,
IERC2981
{
constructor(address characterContractAddress, address signingAddressIn)
ERC721("AdultFantasySeasonOne", "AFC")
{
afCharacter = IAFCharacter(characterContractAddress);
require(address(signingAddressIn) != address(0), "Address is zero");
signingAddress = signingAddressIn;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// Required for verifying mint passes
using ECDSA for bytes32;
/// Reference to the character contract
IAFCharacter afCharacter;
uint256 public boardingGroup = 0; /// Sets the faction that can mint
address public contractIdentifier; /// For verifying mint passes
string public customBaseURI; /// For viewing metadata
string public licenseAgreementURI; /// For viewing the license agreement
bool public mintStarted = false; /// Sets if general sale minting is enabled
uint256 public priceWEI; /// For setting price
uint256 public reservedCardsAvailable = 1000; /// Sets number of reserved cards
address public royaltyTarget; /// Adddress where royalties are to be sent
address public signingAddress; /// For verifying mint passes
/// All cards that have been minted
mapping(uint256 => MintedCard) public mintedCards;
/// Represents a minted card
struct MintedCard {
uint256 characterID;
uint256 specialSauceCode;
uint256 serialNumerator;
uint256 mintTime;
}
/// Types of mints other than general sale
enum MintMethods {
Whitelist,
Giveaway,
Reserved
}
mapping(string => bool) private usedMintPasses;
mapping(address => uint256) public mintCounts;
event BoardingGroupChanged(uint256 newBoardingGroup);
/// Override functions <-----
function _baseURI() internal view override returns (string memory) {
return customBaseURI;
}
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 royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
return (royaltyTarget, (_salePrice * 15) / 200); /// To get 7.5%
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable, AccessControlEnumerable)
returns (bool)
{
return
interfaceId == type(IERC2981).interfaceId ||
super.supportsInterface(interfaceId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
return super.tokenURI(tokenId);
}
/// ----->
/// Mints one token per mint pass provided
/// Mint pass is comprised of mintMethod, messageBoardingGroup, guid, and signature
function purchaseTokenMintPass(
MintMethods mintMethod,
uint256 messageBoardingGroup,
string memory guid,
bytes memory signature,
uint256[] memory randomNumbers,
bytes[] memory signedRandomNumbers
) external payable {
require(
isValidAccessMessage(
mintMethod,
messageBoardingGroup,
guid,
msg.sender,
signature
),
"Invalid token"
);
require(
isValidSignedRandomNumber(randomNumbers[0], signedRandomNumbers[0], msg.sender),
"Random number is invalid"
);
require(!usedMintPasses[guid], "Token has been used");
require(
messageBoardingGroup <= boardingGroup,
"This boarding group is not yet active"
);
usedMintPasses[guid] = true;
mintCounts[msg.sender]++;
uint256 cost = 0 wei;
if (mintMethod == MintMethods.Whitelist) {
/// Otherwise free+gas
cost = priceWEI;
}
/// Ensuring we haven't minted more than the max reserved count
if (
mintMethod == MintMethods.Reserved ||
mintMethod == MintMethods.Giveaway
) {
require(reservedCardsAvailable >= 5); /// 5 are special characters
reservedCardsAvailable--;
}
/// Checking if correct amount sent, could be zero for reserved or giveaway
require(msg.value == cost, ConstantsAF.INCORRECT_AMOUNT);
mintMultiple(1, randomNumbers, msg.sender);
}
/// Mints number of tokens provided during general sale
function purchaseToken(
uint256 purchaseCount,
uint256[] memory randomNumbers,
bytes[] memory signedRandomNumbers
) external payable {
/// Checking to make sure general sale is enabled
require(mintStarted, ConstantsAF.MINT_BEFORE_START);
/// Checking if general sale has sold out
require(totalSupply() < 9000, ConstantsAF.MAIN_SALE_ENDED);
/// Checking if correct amount sent
require(
msg.value == priceWEI * purchaseCount,
ConstantsAF.INCORRECT_AMOUNT
);
/// Checking if purchaseCount is under or equals 10
require(purchaseCount <= 10, ConstantsAF.PURCHACE_TOO_MANY);
for (uint256 index = 0; index < signedRandomNumbers.length; index++) {
uint256 randomNumber = randomNumbers[index];
bytes memory signedRandomNumber = signedRandomNumbers[index];
require(
isValidSignedRandomNumber(randomNumber, signedRandomNumber, msg.sender),
"Random Number is invalid"
);
mintCounts[msg.sender]++;
}
mintMultiple(purchaseCount, randomNumbers, msg.sender);
}
/// For minting a number of mint passes that come from the reserved cards
function batchPurchaseReservedTokenMintPass(
string[] memory guids,
uint256[] memory boardingGroups,
bytes[] memory signatures,
address _addr,
uint256[] memory randomNumbers,
bytes[] memory signedRandomNumbers
) external payable {
require(
guids.length == signatures.length,
"Guid length doesn't match signatures"
);
require(
boardingGroups.length == signatures.length,
"Boarding groups length doesn't match signatures"
);
require(
randomNumbers.length == signatures.length,
"Random numbers length doesn't match signatures"
);
/// Ensuring we haven't minted more than the max reserved count
require(
int256(reservedCardsAvailable) - int256(guids.length) >= 0,
"Not enough reserved cards available"
);
/// Decrement the available reserved cards
reservedCardsAvailable -= guids.length;
/// Validating mint passes
for (uint256 index = 0; index < guids.length; index++) {
/// Validating mint each mint pass
string memory guid = guids[index];
bytes memory signature = signatures[index];
uint256 messageBoardingGroup = boardingGroups[index];
require(
isValidAccessMessage(
MintMethods.Reserved,
messageBoardingGroup,
guid,
_addr,
signature
),
"Access message is invalid"
);
uint256 randomNumber = randomNumbers[index];
bytes memory signedRandomNumber = signedRandomNumbers[index];
require(
isValidSignedRandomNumber(randomNumber, signedRandomNumber, _addr),
"Random number is invalid"
);
require(!usedMintPasses[guid], "Mint pass is used");
require(
boardingGroups[index] <= boardingGroup,
"This boarding group is not yet active"
);
usedMintPasses[guid] = true;
mintCounts[_addr]++;
}
mintMultiple(guids.length, randomNumbers, _addr);
}
/// Mint special characters not available during the presale nor general sale
function mintSpecialCharacter(uint256 characterID, address targetAddress)
external
onlyEditor
{
/// Ensuring we haven't minted more than the max reserved count
require(
int256(reservedCardsAvailable) - 1 >= 0,
"Not enough reserved cards available"
);
/// Decrement the available reserved cards
reservedCardsAvailable -= 1;
/// Recording the minted card
uint256 _id = totalSupply() + 1;
MintedCard storage card = mintedCards[_id];
card.characterID = characterID;
card.specialSauceCode = 0;
card.serialNumerator = 1;
/// Performing the mint
_safeMint(targetAddress, _id);
}
/// Set baseURI for metadata
function setBaseURI(string memory uri) external onlyEditor {
customBaseURI = uri;
}
/// Set faction that is allowed to mint during presale
function setBoardingGroup(uint256 newBoardingGroup) external onlyEditor {
boardingGroup = newBoardingGroup;
emit BoardingGroupChanged(newBoardingGroup);
}
/// Set contractIdentifier for validating mint passes
function setContractIdentifier(address addr) external onlyEditor {
require(address(addr) != address(0), "Address is zero");
contractIdentifier = addr;
}
function setSigningAddress(address addr) external onlyEditor {
require(address(addr) != address(0), "Address is zero");
signingAddress = addr;
}
/// Set licenseURI for license information
function setLicenseURI(string memory uri) external onlyEditor {
licenseAgreementURI = uri;
}
/// Set mintStarted to enable and disable the general sale
function setMintStarted(bool newMintStartedValue) external onlyEditor {
mintStarted = newMintStartedValue;
}
/// Set price for the token
function setPrice(uint256 price) external onlyEditor {
priceWEI = price;
}
/// Set royaltyTarget for the address to receive royalties
/// This is assuming marketplaces will adopt IERC2981
function setRoyaltyTarget(address targetAddress) external onlyEditor {
require(address(targetAddress) != address(0), "Address is zero");
royaltyTarget = targetAddress;
}
/// Withdraw revenue to the contract owner's address
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
Address.sendValue(payable(owner()), balance);
}
/// Get the card info for viewing on marketplaces
function getCard(uint256 cardID) external view returns (MintedCard memory) {
return mintedCards[cardID];
}
/// Validates mint passes
function isValidAccessMessage(
MintMethods mintMethod,
uint256 messageBoardingGroup,
string memory guid,
address _addr,
bytes memory signature
) public view returns (bool) {
bytes32 hash = keccak256(
abi.encodePacked(
uint256(mintMethod),
messageBoardingGroup,
bytes(guid),
contractIdentifier,
_addr
)
);
return
signingAddress == hash.toEthSignedMessageHash().recover(signature);
}
function isValidSignedRandomNumber(
uint256 randomNumber,
bytes memory signedRandomNumber,
address _addr
) public view returns (bool) {
bytes32 hash = keccak256(
abi.encodePacked(
randomNumber,
contractIdentifier,
mintCounts[_addr],
_addr
)
);
return
signingAddress ==
hash.toEthSignedMessageHash().recover(signedRandomNumber);
}
/// Primary minting function
function mintMultiple(
uint256 quantity,
uint256[] memory randomNumbers,
address targetAddress
) private {
for (uint256 index = 0; index < quantity; index++) {
///Selecting random character
uint256 totalRemaining = 9995 - totalSupply(); /// 5 are special characters
uint256 characterID = afCharacter.takeRandomCharacter(
randomNumbers[index], totalRemaining
);
/// Setting serial numerator
uint256 serialNumerator = afCharacter.getCharacterSupply(
characterID
);
/// Recording the minted card
uint256 _id = totalSupply() + 1;
MintedCard storage card = mintedCards[_id];
card.characterID = characterID;
card.specialSauceCode = randomNumbers[index];
card.serialNumerator = serialNumerator;
card.mintTime = block.timestamp;
/// Delete variables
delete serialNumerator;
delete characterID;
delete totalRemaining;
/// Performing the mint
_safeMint(targetAddress, _id);
}
}
}
/// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.9;
interface IERC2981 {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
/// _registerInterface(_INTERFACE_ID_ERC2981);
/// @notice Called with the sale price to determine how much royalty
/// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
/// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.9;
interface IAFCharacter {
function takeRandomCharacter(uint256 randomNumber, uint256 totalRemaining) external returns (uint256);
function getCharacterSupply(uint256 characterID)
external
view
returns (uint256);
}
/// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.9;
library ConstantsAF {
/// Error messages
string public constant MINT_BEFORE_START = "Sale not started";
string public constant INCORRECT_AMOUNT = "Incorrect amount sent";
string public constant PURCHACE_TOO_MANY = "Quantity was greater than 20";
string public constant NO_CHARACTERS = "No characters are available";
string public constant INVALID_CHARACTER = "Non-existent character";
string public constant MAIN_SALE_ENDED = "Main sale has ended";
/// Role managers can add and remove users from roles
bytes32 public constant ROLE_MANAGER_ROLE = keccak256("ROLE_MANAGER_ROLE");
/// Editors can modify certain properties on the contract
bytes32 public constant EDITOR_ROLE = keccak256("EDITOR_ROLE");
/// This role enables other contracts to call functions, but not the general public
bytes32 public constant CONTRACT_ROLE = keccak256("CONTRACT_ROLE");
}
/// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/AccessControlEnumerable.sol";
import "./ConstantsAF.sol";
abstract contract AFRoles is AccessControlEnumerable {
modifier onlyEditor() {
require(
hasRole(ConstantsAF.EDITOR_ROLE, msg.sender),
"Caller is not an editor"
);
_;
}
modifier onlyContract() {
require(
hasRole(ConstantsAF.CONTRACT_ROLE, msg.sender),
"Caller is not a contract"
);
_;
}
function setRole(bytes32 role, address user) external {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender) ||
hasRole(ConstantsAF.ROLE_MANAGER_ROLE, msg.sender),
"Caller is not admin nor role manager"
);
_setupRole(role, user);
}
}
// 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 Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
/**
* @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];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
| / For verifying mint passes
| address public contractIdentifier; | 12,602,761 | [
1,
19,
2457,
3929,
310,
312,
474,
11656,
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,
1758,
1071,
6835,
3004,
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
]
|
./full_match/5/0xba077F187033094b43cD2336103a8b40Ba20545d/sources/contracts/PrmntOrigin.sol | 100%{transform:rotate(360deg) scale(1);
| " @keyframes r1{0%{transform:rotate(0deg) scale(1);}50%{transform:rotate(180deg) scale(1.4);}}}", | 1,859,810 | [
1,
6625,
9,
95,
6547,
30,
20342,
12,
29751,
9923,
13,
3159,
12,
21,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
5411,
315,
632,
856,
10278,
436,
21,
95,
20,
9,
95,
6547,
30,
20342,
12,
20,
9923,
13,
3159,
12,
21,
1769,
97,
3361,
9,
95,
6547,
30,
20342,
12,
18278,
9923,
13,
3159,
12,
21,
18,
24,
1769,
9090,
1532,
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
]
|
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.7.1;
import "./BaseSalary.sol";
/// @title "Salary" that is paid one token per second using minted conditionals.
/// @author Victor Porton
/// @notice Not audited, not enough tested.
contract Salary is BaseSalary {
/// @param _uri The ERC-1155 token URI.
constructor(string memory _uri) BaseSalary(_uri) { }
/// Register a salary recipient.
///
/// Can be called both before or after the oracle finish. However registering after the finish is useless.
///
/// Anyone can register anyone (useful for robots registering a person).
///
/// Registering another person is giving him money against his will (forcing to hire bodyguards, etc.),
/// but if one does not want, he can just not associate this address with his identity in his publications.
/// @param _customer The original address.
/// @param _oracleId The oracle ID.
/// @param _data The current data.
function registerCustomer(address _customer, uint64 _oracleId, bytes calldata _data)
virtual public returns (uint256)
{
return _registerCustomer(_customer, _oracleId, _data);
}
} | @param _uri The ERC-1155 token URI. | constructor(string memory _uri) BaseSalary(_uri) { }
| 12,897,650 | [
1,
67,
1650,
1021,
4232,
39,
17,
2499,
2539,
1147,
3699,
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
]
| [
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,
3885,
12,
1080,
3778,
389,
1650,
13,
3360,
55,
287,
814,
24899,
1650,
13,
288,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: GPL-3.0-only
// ┏━━━┓━━━━━┏┓━━━━━━━━━┏━━━┓━━━━━━━━━━━━━━━━━━━━━━━
// ┃┏━┓┃━━━━┏┛┗┓━━━━━━━━┃┏━━┛━━━━━━━━━━━━━━━━━━━━━━━
// ┃┗━┛┃┏━┓━┗┓┏┛┏━━┓━━━━┃┗━━┓┏┓┏━┓━┏━━┓━┏━┓━┏━━┓┏━━┓
// ┃┏━┓┃┃┏┓┓━┃┃━┃┏┓┃━━━━┃┏━━┛┣┫┃┏┓┓┗━┓┃━┃┏┓┓┃┏━┛┃┏┓┃
// ┃┃ ┃┃┃┃┃┃━┃┗┓┃┃━┫━┏┓━┃┃━━━┃┃┃┃┃┃┃┗┛┗┓┃┃┃┃┃┗━┓┃┃━┫
// ┗┛ ┗┛┗┛┗┛━┗━┛┗━━┛━┗┛━┗┛━━━┗┛┗┛┗┛┗━━━┛┗┛┗┛┗━━┛┗━━┛
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
pragma solidity ^0.8.0;
import {AnteTest} from "../AnteTest.sol";
import {IRibbonThetaVault} from "./ribbon-v2-contracts/interfaces/IRibbonThetaVault.sol";
import {IController, GammaTypes} from "./ribbon-v2-contracts/interfaces/GammaInterface.sol";
import {Vault} from "./ribbon-v2-contracts/libraries/Vault.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Checks that RibbonV2 Theta vaults do not lose 90% of their assets
/// @notice Ante Test to check if a catastrophic failure has occured in RibbonV2
contract AnteRibbonV2ThetaVaultPlungeTest is AnteTest("RibbonV2 doesn't lose 90% of its TVL") {
// currently deployed RibbonV2 theta vaults
IRibbonThetaVault[2] public thetaVaults = [
IRibbonThetaVault(0x25751853Eab4D0eB3652B5eB6ecB102A2789644B), // eth vault
IRibbonThetaVault(0x65a833afDc250D9d38f8CD9bC2B1E3132dB13B2F) // wbtc vault
];
// Opyn Controller
IController internal controller = IController(0x4ccc2339F87F6c59c6893E1A678c2266cA58dC72);
// threshold amounts for test to fail
uint256[2] public thresholds;
/// @notice percent drop threshold (set to 10%)
uint8 public constant PERCENT_DROP_THRESHOLD = 10;
constructor() {
protocolName = "Ribbon";
for (uint256 i; i < thetaVaults.length; i++) {
thresholds[i] = (calculateAssetBalance(thetaVaults[i]) * PERCENT_DROP_THRESHOLD) / 100;
testedContracts.push(address(thetaVaults[i]));
}
}
/// @notice computes balance of underlying asset in a given Ribbon Theta Vault
/// @param vault RibbonV2 Theta Vault address
/// @return balance of vault
function calculateAssetBalance(IRibbonThetaVault vault) public view returns (uint256) {
Vault.VaultParams memory vaultParams = vault.vaultParams();
IERC20 underlying = IERC20(vaultParams.underlying);
GammaTypes.Vault memory opynVault = controller.getVault(
address(vault),
controller.getAccountVaultCounter(address(vault))
);
// make assumption that there is only one collateral asset in vault
return underlying.balanceOf(address(vault)) + opynVault.collateralAmounts[0];
}
/// @notice checks balance of Ribbon Theta V2 vaults against threshold
/// (10% of balance when this contract was deployed)
/// @return true if balance of all theta vaults is greater than thresholds
function checkTestPasses() external view override returns (bool) {
for (uint256 i; i < thetaVaults.length; i++) {
if (calculateAssetBalance(thetaVaults[i]) < thresholds[i]) {
return false;
}
}
return true;
}
}
// SPDX-License-Identifier: GPL-3.0-only
// ┏━━━┓━━━━━┏┓━━━━━━━━━┏━━━┓━━━━━━━━━━━━━━━━━━━━━━━
// ┃┏━┓┃━━━━┏┛┗┓━━━━━━━━┃┏━━┛━━━━━━━━━━━━━━━━━━━━━━━
// ┃┗━┛┃┏━┓━┗┓┏┛┏━━┓━━━━┃┗━━┓┏┓┏━┓━┏━━┓━┏━┓━┏━━┓┏━━┓
// ┃┏━┓┃┃┏┓┓━┃┃━┃┏┓┃━━━━┃┏━━┛┣┫┃┏┓┓┗━┓┃━┃┏┓┓┃┏━┛┃┏┓┃
// ┃┃ ┃┃┃┃┃┃━┃┗┓┃┃━┫━┏┓━┃┃━━━┃┃┃┃┃┃┃┗┛┗┓┃┃┃┃┃┗━┓┃┃━┫
// ┗┛ ┗┛┗┛┗┛━┗━┛┗━━┛━┗┛━┗┛━━━┗┛┗┛┗┛┗━━━┛┗┛┗┛┗━━┛┗━━┛
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
pragma solidity >=0.7.0;
import "./interfaces/IAnteTest.sol";
/// @title Ante V0.5 Ante Test smart contract
/// @notice Abstract inheritable contract that supplies syntactic sugar for writing Ante Tests
/// @dev Usage: contract YourAnteTest is AnteTest("String descriptor of test") { ... }
abstract contract AnteTest is IAnteTest {
/// @inheritdoc IAnteTest
address public override testAuthor;
/// @inheritdoc IAnteTest
string public override testName;
/// @inheritdoc IAnteTest
string public override protocolName;
/// @inheritdoc IAnteTest
address[] public override testedContracts;
/// @dev testedContracts and protocolName are optional parameters which should
/// be set in the constructor of your AnteTest
/// @param _testName The name of the Ante Test
constructor(string memory _testName) {
testAuthor = msg.sender;
testName = _testName;
}
/// @notice Returns the testedContracts array of addresses
/// @return The list of tested contracts as an array of addresses
function getTestedContracts() external view returns (address[] memory) {
return testedContracts;
}
/// @inheritdoc IAnteTest
function checkTestPasses() external virtual override returns (bool) {}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {Vault} from "../libraries/Vault.sol";
interface IRibbonThetaVault {
function GAMMA_CONTROLLER() external view returns (address);
function currentOption() external view returns (address);
function nextOption() external view returns (address);
function vaultParams() external view returns (Vault.VaultParams memory);
function vaultState() external view returns (Vault.VaultState memory);
function optionState() external view returns (Vault.OptionState memory);
function optionAuctionID() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
library GammaTypes {
// vault is a struct of 6 arrays that describe a position a user has, a user can have multiple vaults.
struct Vault {
// addresses of oTokens a user has shorted (i.e. written) against this vault
address[] shortOtokens;
// addresses of oTokens a user has bought and deposited in this vault
// user can be long oTokens without opening a vault (e.g. by buying on a DEX)
// generally, long oTokens will be 'deposited' in vaults to act as collateral
// in order to write oTokens against (i.e. in spreads)
address[] longOtokens;
// addresses of other ERC-20s a user has deposited as collateral in this vault
address[] collateralAssets;
// quantity of oTokens minted/written for each oToken address in shortOtokens
uint256[] shortAmounts;
// quantity of oTokens owned and held in the vault for each oToken address in longOtokens
uint256[] longAmounts;
// quantity of ERC-20 deposited as collateral in the vault for each ERC-20 address in collateralAssets
uint256[] collateralAmounts;
}
}
interface IOtoken {
function underlyingAsset() external view returns (address);
function strikeAsset() external view returns (address);
function collateralAsset() external view returns (address);
function strikePrice() external view returns (uint256);
function expiryTimestamp() external view returns (uint256);
function isPut() external view returns (bool);
}
interface IOtokenFactory {
function getOtoken(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external view returns (address);
function createOtoken(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external returns (address);
function getTargetOtokenAddress(
address _underlyingAsset,
address _strikeAsset,
address _collateralAsset,
uint256 _strikePrice,
uint256 _expiry,
bool _isPut
) external view returns (address);
event OtokenCreated(
address tokenAddress,
address creator,
address indexed underlying,
address indexed strike,
address indexed collateral,
uint256 strikePrice,
uint256 expiry,
bool isPut
);
}
interface IController {
// possible actions that can be performed
enum ActionType {
OpenVault,
MintShortOption,
BurnShortOption,
DepositLongOption,
WithdrawLongOption,
DepositCollateral,
WithdrawCollateral,
SettleVault,
Redeem,
Call,
Liquidate
}
struct ActionArgs {
// type of action that is being performed on the system
ActionType actionType;
// address of the account owner
address owner;
// address which we move assets from or to (depending on the action type)
address secondAddress;
// asset that is to be transfered
address asset;
// index of the vault that is to be modified (if any)
uint256 vaultId;
// amount of asset that is to be transfered
uint256 amount;
// each vault can hold multiple short / long / collateral assets
// but we are restricting the scope to only 1 of each in this version
// in future versions this would be the index of the short / long / collateral asset that needs to be modified
uint256 index;
// any other data that needs to be passed in for arbitrary function calls
bytes data;
}
struct RedeemArgs {
// address to which we pay out the oToken proceeds
address receiver;
// oToken that is to be redeemed
address otoken;
// amount of oTokens that is to be redeemed
uint256 amount;
}
function getPayout(address _otoken, uint256 _amount) external view returns (uint256);
function operate(ActionArgs[] calldata _actions) external;
function getAccountVaultCounter(address owner) external view returns (uint256);
function oracle() external view returns (address);
function getVault(address _owner, uint256 _vaultId) external view returns (GammaTypes.Vault memory);
function getProceed(address _owner, uint256 _vaultId) external view returns (uint256);
function isSettlementAllowed(
address _underlying,
address _strike,
address _collateral,
uint256 _expiry
) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
library Vault {
/************************************************
* IMMUTABLES & CONSTANTS
***********************************************/
// Fees are 6-decimal places. For example: 20 * 10**6 = 20%
uint256 internal constant FEE_MULTIPLIER = 10**6;
// Premium discount has 1-decimal place. For example: 80 * 10**1 = 80%. Which represents a 20% discount.
uint256 internal constant PREMIUM_DISCOUNT_MULTIPLIER = 10;
// Otokens have 8 decimal places.
uint256 internal constant OTOKEN_DECIMALS = 8;
// Percentage of funds allocated to options is 2 decimal places. 10 * 10**2 = 10%
uint256 internal constant OPTION_ALLOCATION_MULTIPLIER = 10**2;
// Placeholder uint value to prevent cold writes
uint256 internal constant PLACEHOLDER_UINT = 1;
struct VaultParams {
// Option type the vault is selling
bool isPut;
// Token decimals for vault shares
uint8 decimals;
// Asset used in Theta / Delta Vault
address asset;
// Underlying asset of the options sold by vault
address underlying;
// Minimum supply of the vault shares issued, for ETH it's 10**10
uint56 minimumSupply;
// Vault cap
uint104 cap;
}
struct OptionState {
// Option that the vault is shorting / longing in the next cycle
address nextOption;
// Option that the vault is currently shorting / longing
address currentOption;
// The timestamp when the `nextOption` can be used by the vault
uint32 nextOptionReadyAt;
}
struct VaultState {
// 32 byte slot 1
// Current round number. `round` represents the number of `period`s elapsed.
uint16 round;
// Amount that is currently locked for selling options
uint104 lockedAmount;
// Amount that was locked for selling options in the previous round
// used for calculating performance fee deduction
uint104 lastLockedAmount;
// 32 byte slot 2
// Stores the total tally of how much of `asset` there is
// to be used to mint rTHETA tokens
uint128 totalPending;
// Amount locked for scheduled withdrawals;
uint128 queuedWithdrawShares;
}
struct DepositReceipt {
// Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years.
uint16 round;
// Deposit amount, max 20,282,409,603,651 or 20 trillion ETH deposit
uint104 amount;
// Unredeemed shares balance
uint128 unredeemedShares;
}
struct Withdrawal {
// Maximum of 65535 rounds. Assuming 1 round is 7 days, maximum is 1256 years.
uint16 round;
// Number of shares withdrawn
uint128 shares;
}
struct AuctionSellOrder {
// Amount of `asset` token offered in auction
uint96 sellAmount;
// Amount of oToken requested in auction
uint96 buyAmount;
// User Id of delta vault in latest gnosis auction
uint64 userId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0-only
// ┏━━━┓━━━━━┏┓━━━━━━━━━┏━━━┓━━━━━━━━━━━━━━━━━━━━━━━
// ┃┏━┓┃━━━━┏┛┗┓━━━━━━━━┃┏━━┛━━━━━━━━━━━━━━━━━━━━━━━
// ┃┗━┛┃┏━┓━┗┓┏┛┏━━┓━━━━┃┗━━┓┏┓┏━┓━┏━━┓━┏━┓━┏━━┓┏━━┓
// ┃┏━┓┃┃┏┓┓━┃┃━┃┏┓┃━━━━┃┏━━┛┣┫┃┏┓┓┗━┓┃━┃┏┓┓┃┏━┛┃┏┓┃
// ┃┃ ┃┃┃┃┃┃━┃┗┓┃┃━┫━┏┓━┃┃━━━┃┃┃┃┃┃┃┗┛┗┓┃┃┃┃┃┗━┓┃┃━┫
// ┗┛ ┗┛┗┛┗┛━┗━┛┗━━┛━┗┛━┗┛━━━┗┛┗┛┗┛┗━━━┛┗┛┗┛┗━━┛┗━━┛
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
pragma solidity >=0.7.0;
/// @title The interface for the Ante V0.5 Ante Test
/// @notice The Ante V0.5 Ante Test wraps test logic for verifying fundamental invariants of a protocol
interface IAnteTest {
/// @notice Returns the author of the Ante Test
/// @dev This overrides the auto-generated getter for testAuthor as a public var
/// @return The address of the test author
function testAuthor() external view returns (address);
/// @notice Returns the name of the protocol the Ante Test is testing
/// @dev This overrides the auto-generated getter for protocolName as a public var
/// @return The name of the protocol in string format
function protocolName() external view returns (string memory);
/// @notice Returns a single address in the testedContracts array
/// @dev This overrides the auto-generated getter for testedContracts [] as a public var
/// @param i The array index of the address to return
/// @return The address of the i-th element in the list of tested contracts
function testedContracts(uint256 i) external view returns (address);
/// @notice Returns the name of the Ante Test
/// @dev This overrides the auto-generated getter for testName as a public var
/// @return The name of the Ante Test in string format
function testName() external view returns (string memory);
/// @notice Function containing test logic to inspect the protocol invariant
/// @dev This should usually return True
/// @return A single bool indicating if the Ante Test passes/fails
function checkTestPasses() external returns (bool);
} | Option type the vault is selling Token decimals for vault shares Asset used in Theta / Delta Vault Underlying asset of the options sold by vault Minimum supply of the vault shares issued, for ETH it's 10**10 Vault cap | function getPayout(address _otoken, uint256 _amount) external view returns (uint256);
function operate(ActionArgs[] calldata _actions) external;
function getAccountVaultCounter(address owner) external view returns (uint256);
function oracle() external view returns (address);
function getVault(address _owner, uint256 _vaultId) external view returns (GammaTypes.Vault memory);
function getProceed(address _owner, uint256 _vaultId) external view returns (uint256);
function isSettlementAllowed(
address _underlying,
address _strike,
address _collateral,
uint256 _expiry
) external view returns (bool);
}
pragma solidity =0.8.4;
struct VaultParams {
bool isPut;
uint8 decimals;
address asset;
address underlying;
uint56 minimumSupply;
uint104 cap;
}
| 6,874,988 | [
1,
1895,
618,
326,
9229,
353,
357,
2456,
3155,
15105,
364,
9229,
24123,
10494,
1399,
316,
935,
1066,
342,
17799,
17329,
21140,
6291,
3310,
434,
326,
702,
272,
1673,
635,
9229,
23456,
14467,
434,
326,
9229,
24123,
16865,
16,
364,
512,
2455,
518,
1807,
13822,
20,
17329,
3523,
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,
565,
445,
1689,
2012,
12,
2867,
389,
352,
969,
16,
2254,
5034,
389,
8949,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
20829,
12,
1803,
2615,
8526,
745,
892,
389,
4905,
13,
3903,
31,
203,
203,
565,
445,
23393,
12003,
4789,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
20865,
1435,
3903,
1476,
1135,
261,
2867,
1769,
203,
203,
565,
445,
11031,
3714,
12,
2867,
389,
8443,
16,
2254,
5034,
389,
26983,
548,
13,
3903,
1476,
1135,
261,
31300,
2016,
18,
12003,
3778,
1769,
203,
203,
565,
445,
3570,
5288,
12,
2867,
389,
8443,
16,
2254,
5034,
389,
26983,
548,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
13532,
88,
806,
5042,
12,
203,
3639,
1758,
389,
9341,
6291,
16,
203,
3639,
1758,
389,
701,
2547,
16,
203,
3639,
1758,
389,
12910,
2045,
287,
16,
203,
3639,
2254,
5034,
389,
22409,
203,
565,
262,
3903,
1476,
1135,
261,
6430,
1769,
203,
97,
203,
203,
683,
9454,
18035,
560,
273,
20,
18,
28,
18,
24,
31,
203,
203,
565,
1958,
17329,
1370,
288,
203,
3639,
1426,
353,
6426,
31,
203,
3639,
2254,
28,
15105,
31,
203,
3639,
1758,
3310,
31,
203,
3639,
1758,
6808,
31,
203,
3639,
2254,
4313,
5224,
3088,
1283,
31,
203,
3639,
2254,
21869,
3523,
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
]
|
./full_match/4/0xb52f1DAb6E7dBa3c7a34D1b71866B9ED196086b2/sources/dinocrypto.sol | * the Metadata extension, but not including the Enumerable extension, which is available separately as {ERC721Enumerable}./ Token name Token symbol Mapping from token ID to owner address Mapping owner address to token count Mapping from token ID to approved address Mapping from owner to operator approvals | contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
mapping(uint256 => address) private _owners;
mapping(address => uint256) private _balances;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
}
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
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;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
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())) : "";
}
function _baseURI() internal view virtual returns (string memory) {
return "";
}
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);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
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);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
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");
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
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));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
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"
);
}
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);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
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);
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
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;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
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;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} catch (bytes memory reason) {
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;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
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;
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
assembly {
revert(add(32, reason), mload(reason))
}
}
}
return true;
}
}
} else {
) internal virtual {}
}
| 738,260 | [
1,
5787,
6912,
2710,
16,
1496,
486,
6508,
326,
6057,
25121,
2710,
16,
1492,
353,
2319,
18190,
487,
288,
654,
39,
27,
5340,
3572,
25121,
5496,
19,
3155,
508,
3155,
3273,
9408,
628,
1147,
1599,
358,
3410,
1758,
9408,
3410,
1758,
358,
1147,
1056,
9408,
628,
1147,
1599,
358,
20412,
1758,
9408,
628,
3410,
358,
3726,
6617,
4524,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
16351,
4232,
39,
27,
5340,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
2277,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
533,
3238,
389,
529,
31,
203,
203,
565,
533,
3238,
389,
7175,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
995,
414,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
2316,
12053,
4524,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
97,
203,
203,
203,
203,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
565,
289,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
12,
654,
39,
28275,
16,
467,
654,
39,
28275,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
2934,
5831,
548,
747,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
27,
5340,
2277,
2934,
5831,
548,
747,
203,
5411,
2240,
18,
28064,
1358,
12,
5831,
548,
1769,
203,
565,
289,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
1071,
1476,
5024,
2
]
|
./full_match/43114/0xCD90d82F42ab965E34a495eD25F4488fcb056Ca4/sources/FROG.sol | * @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/ First check most recent balance Next check implicit zero balance | function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "LYD::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 4,577,775 | [
1,
8519,
326,
6432,
1300,
434,
19588,
364,
392,
2236,
487,
434,
279,
1203,
1300,
225,
3914,
1300,
1297,
506,
279,
727,
1235,
1203,
578,
469,
333,
445,
903,
15226,
358,
5309,
7524,
13117,
18,
225,
2236,
1021,
1758,
434,
326,
2236,
358,
866,
225,
1203,
1854,
1021,
1203,
1300,
358,
336,
326,
12501,
11013,
622,
327,
1021,
1300,
434,
19588,
326,
2236,
9323,
487,
434,
326,
864,
1203,
19,
5783,
866,
4486,
8399,
11013,
4804,
866,
10592,
3634,
11013,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
1689,
2432,
29637,
12,
2867,
2236,
16,
2254,
1203,
1854,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
2583,
12,
2629,
1854,
411,
1203,
18,
2696,
16,
315,
7076,
40,
2866,
588,
25355,
29637,
30,
486,
4671,
11383,
8863,
203,
203,
3639,
2254,
1578,
290,
1564,
4139,
273,
818,
1564,
4139,
63,
4631,
15533,
203,
3639,
309,
261,
82,
1564,
4139,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
2080,
1768,
1648,
1203,
1854,
13,
288,
203,
5411,
327,
26402,
63,
4631,
6362,
82,
1564,
4139,
300,
404,
8009,
27800,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
1893,
4139,
63,
4631,
6362,
20,
8009,
2080,
1768,
405,
1203,
1854,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
203,
3639,
2254,
1578,
2612,
273,
374,
31,
203,
3639,
2254,
1578,
3854,
273,
290,
1564,
4139,
300,
404,
31,
203,
3639,
1323,
261,
5797,
405,
2612,
13,
288,
203,
5411,
25569,
3778,
3283,
273,
26402,
63,
4631,
6362,
5693,
15533,
203,
5411,
309,
261,
4057,
18,
2080,
1768,
422,
1203,
1854,
13,
288,
203,
7734,
327,
3283,
18,
27800,
31,
203,
7734,
2612,
273,
4617,
31,
203,
7734,
3854,
273,
4617,
300,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
26402,
63,
4631,
6362,
8167,
8009,
27800,
31,
203,
565,
289,
203,
203,
2,
-100,
-100
]
|
pragma solidity ^0.5.3;
pragma experimental ABIEncoderV2;
import "./IAddressRegistry.sol";
import "./IErc20.sol";
import "./IPoMain.sol";
import "./IFunding.sol";
import "./IWalletBase.sol";
import "./IBusinessPartnerStorage.sol";
import "./StringLib.sol";
import "./Debuggable.sol";
/// @notice Helper contract for reconfiguring application layer after a redeployment
contract ConfigurationHelper is Debuggable
{
IAddressRegistry public addressRegistry;
IPoMain public poMain;
IFunding public funding;
IWalletBase public walletBuyer01;
IWalletBase public walletBuyer02;
IWalletBase public walletSeller01;
IWalletBase public walletSeller02;
IBusinessPartnerStorage public businessPartnerStorage;
IErc20 public erc20;
string constant private PO_MAIN = "PoMain";
string constant private FUNDING = "Funding";
string constant private PO_STORAGE = "PoStorage";
string constant private PRODUCT_STORAGE = "ProductStorage";
string constant private BUSINESS_PARTNER_STORAGE = "BusinessPartnerStorage";
string constant private SYS_ID_AS_STRING_BUYER_01 = "OmniConsumerProducts";
string constant private SYS_ID_AS_STRING_BUYER_02 = "CyberdyneSystems";
string constant private SYS_ID_AS_STRING_SELLER_01 = "SoylentCorporation";
string constant private SYS_ID_AS_STRING_SELLER_02 = "SoylentUk";
// bytes32 representations of above
bytes32 constant private SYS_ID_BUYER_01 = 0x4f6d6e69436f6e73756d657250726f6475637473000000000000000000000000;
bytes32 constant private SYS_ID_BUYER_02 = 0x437962657264796e6553797374656d7300000000000000000000000000000000;
bytes32 constant private SYS_ID_SELLER_01 = 0x536f796c656e74436f72706f726174696f6e0000000000000000000000000000;
bytes32 constant private SYS_ID_SELLER_02 = 0x536f796c656e74556b0000000000000000000000000000000000000000000000;
constructor (address contractAddressOfRegistry) public
{
addressRegistry = IAddressRegistry(contractAddressOfRegistry);
// Default to showing debug messages
isDebugOn = true;
}
function replaceAppLayer(address addressOfPoMain, address addressOfFunding,
address addressOfWalletBuyer01, address addressOfWalletBuyer02,
address addressOfWalletSeller01, address addressOfWalletSeller02) public
{
// Step 1 - contract deployment, still done manually
// Step 2 - replace address registry entries
addressRegistry.registerAddressString(PO_MAIN, addressOfPoMain);
addressRegistry.registerAddressString(FUNDING, addressOfFunding);
// Step 3 - call configure on all new contracts
// PoMain (get from registry which we just updated)
poMain = IPoMain(addressRegistry.getAddressString(PO_MAIN));
if (address(poMain) != address(0))
{
poMain.configure(PO_STORAGE, PRODUCT_STORAGE, BUSINESS_PARTNER_STORAGE, FUNDING);
}
else
{
logDebugString("Po main not found in registry");
}
// Funding (get from registry which we just updated)
funding = IFunding(addressRegistry.getAddressString(FUNDING));
if (address(funding) != address(0))
{
funding.configure(PO_STORAGE, PO_MAIN, BUSINESS_PARTNER_STORAGE);
}
else
{
logDebugString("Funding not found in registry");
}
// Wallets of Buyers
if (addressOfWalletBuyer01 != address(0))
{
walletBuyer01 = IWalletBase(addressOfWalletBuyer01);
walletBuyer01.configure(SYS_ID_AS_STRING_BUYER_01, PO_MAIN, FUNDING);
}
else
{
logDebugString("WalletBuyer01 not configured");
}
if (addressOfWalletBuyer02 != address(0))
{
walletBuyer02 = IWalletBase(addressOfWalletBuyer02);
walletBuyer02.configure(SYS_ID_AS_STRING_BUYER_02, PO_MAIN, FUNDING);
}
else
{
logDebugString("WalletBuyer02 not configured");
}
// Wallets of Sellers
if (addressOfWalletSeller01 != address(0))
{
walletSeller01 = IWalletBase(addressOfWalletSeller01);
walletSeller01.configure(SYS_ID_AS_STRING_SELLER_01, PO_MAIN, FUNDING);
}
else
{
logDebugString("WalletSeller01 not configured");
}
if (addressOfWalletSeller02 != address(0))
{
walletSeller02 = IWalletBase(addressOfWalletSeller02);
walletSeller02.configure(SYS_ID_AS_STRING_SELLER_02, PO_MAIN, FUNDING);
}
else
{
logDebugString("WalletSeller02 not configured");
}
// Step 4 - call business partner storage to update wallets addresses
businessPartnerStorage = IBusinessPartnerStorage(addressRegistry.getAddressString(BUSINESS_PARTNER_STORAGE));
if (address(businessPartnerStorage) != address(0))
{
businessPartnerStorage.setWalletAddress(SYS_ID_BUYER_01, addressOfWalletBuyer01);
businessPartnerStorage.setWalletAddress(SYS_ID_BUYER_02, addressOfWalletBuyer02);
businessPartnerStorage.setWalletAddress(SYS_ID_SELLER_01, addressOfWalletSeller01);
businessPartnerStorage.setWalletAddress(SYS_ID_SELLER_02, addressOfWalletSeller02);
}
else
{
logDebugString("businessPartnerStorage not found in registry");
}
logDebugString("Completed replaceAppLayer");
}
//function transferTokensToWalletBuyer(address addressOfWalletBuyer, address addressOfTokens) public payable
//{
// // Step 5 - transfer MOCKDAI to buyer wallet for spending
// erc20 = IErc20(addressOfTokens);
// erc20.transfer(addressOfWalletBuyer, 1000);
//
// logDebugString("Completed transfer tokens");
//}
}
| Step 1 - contract deployment, still done manually Step 2 - replace address registry entries Step 3 - call configure on all new contracts PoMain (get from registry which we just updated) | function replaceAppLayer(address addressOfPoMain, address addressOfFunding,
address addressOfWalletBuyer01, address addressOfWalletBuyer02,
address addressOfWalletSeller01, address addressOfWalletSeller02) public
{
addressRegistry.registerAddressString(PO_MAIN, addressOfPoMain);
addressRegistry.registerAddressString(FUNDING, addressOfFunding);
poMain = IPoMain(addressRegistry.getAddressString(PO_MAIN));
if (address(poMain) != address(0))
{
poMain.configure(PO_STORAGE, PRODUCT_STORAGE, BUSINESS_PARTNER_STORAGE, FUNDING);
}
else
{
logDebugString("Po main not found in registry");
}
if (address(funding) != address(0))
{
funding.configure(PO_STORAGE, PO_MAIN, BUSINESS_PARTNER_STORAGE);
}
else
{
logDebugString("Funding not found in registry");
}
{
walletBuyer01 = IWalletBase(addressOfWalletBuyer01);
walletBuyer01.configure(SYS_ID_AS_STRING_BUYER_01, PO_MAIN, FUNDING);
}
else
{
logDebugString("WalletBuyer01 not configured");
}
if (addressOfWalletBuyer02 != address(0))
{
walletBuyer02 = IWalletBase(addressOfWalletBuyer02);
walletBuyer02.configure(SYS_ID_AS_STRING_BUYER_02, PO_MAIN, FUNDING);
}
else
{
logDebugString("WalletBuyer02 not configured");
}
{
walletSeller01 = IWalletBase(addressOfWalletSeller01);
walletSeller01.configure(SYS_ID_AS_STRING_SELLER_01, PO_MAIN, FUNDING);
}
else
{
logDebugString("WalletSeller01 not configured");
}
if (addressOfWalletSeller02 != address(0))
{
walletSeller02 = IWalletBase(addressOfWalletSeller02);
walletSeller02.configure(SYS_ID_AS_STRING_SELLER_02, PO_MAIN, FUNDING);
}
else
{
logDebugString("WalletSeller02 not configured");
}
if (address(businessPartnerStorage) != address(0))
{
businessPartnerStorage.setWalletAddress(SYS_ID_BUYER_01, addressOfWalletBuyer01);
businessPartnerStorage.setWalletAddress(SYS_ID_BUYER_02, addressOfWalletBuyer02);
businessPartnerStorage.setWalletAddress(SYS_ID_SELLER_01, addressOfWalletSeller01);
businessPartnerStorage.setWalletAddress(SYS_ID_SELLER_02, addressOfWalletSeller02);
}
else
{
logDebugString("businessPartnerStorage not found in registry");
}
logDebugString("Completed replaceAppLayer");
}
| 15,803,070 | [
1,
4160,
404,
300,
6835,
6314,
16,
4859,
2731,
10036,
8693,
576,
300,
1453,
1758,
4023,
3222,
8693,
890,
300,
745,
5068,
603,
777,
394,
20092,
453,
83,
6376,
261,
588,
628,
4023,
1492,
732,
2537,
3526,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
1453,
3371,
4576,
12,
2867,
1758,
951,
29198,
6376,
16,
1758,
1758,
951,
42,
14351,
16,
203,
3639,
1758,
1758,
951,
16936,
38,
16213,
1611,
16,
225,
1758,
1758,
951,
16936,
38,
16213,
3103,
16,
203,
3639,
1758,
1758,
951,
16936,
22050,
1611,
16,
1758,
1758,
951,
16936,
22050,
3103,
13,
1071,
203,
565,
288,
203,
540,
203,
3639,
1758,
4243,
18,
4861,
1887,
780,
12,
2419,
67,
19803,
16,
1758,
951,
29198,
6376,
1769,
203,
3639,
1758,
4243,
18,
4861,
1887,
780,
12,
42,
5240,
1360,
16,
1758,
951,
42,
14351,
1769,
203,
540,
203,
3639,
8275,
6376,
273,
2971,
83,
6376,
12,
2867,
4243,
18,
588,
1887,
780,
12,
2419,
67,
19803,
10019,
203,
3639,
309,
261,
2867,
12,
1631,
6376,
13,
480,
1758,
12,
20,
3719,
203,
3639,
288,
203,
5411,
8275,
6376,
18,
14895,
12,
2419,
67,
19009,
16,
27958,
67,
19009,
16,
605,
3378,
3740,
1260,
67,
15055,
12196,
67,
19009,
16,
478,
5240,
1360,
1769,
203,
3639,
289,
203,
3639,
469,
203,
3639,
288,
203,
5411,
613,
2829,
780,
2932,
29198,
2774,
486,
1392,
316,
4023,
8863,
203,
3639,
289,
203,
203,
3639,
309,
261,
2867,
12,
74,
14351,
13,
480,
1758,
12,
20,
3719,
203,
3639,
288,
203,
5411,
22058,
18,
14895,
12,
2419,
67,
19009,
16,
13803,
67,
19803,
16,
605,
3378,
3740,
1260,
67,
15055,
12196,
67,
19009,
1769,
203,
3639,
289,
203,
3639,
469,
203,
3639,
288,
203,
5411,
613,
2829,
780,
2932,
42,
14351,
486,
1392,
316,
4023,
8863,
203,
3639,
2
]
|
./full_match/5/0x2983062d627611cddC53E8Dcff6a81CD3c71EbA3/sources/project_/contracts/Miragrow.sol | address payable private constant _walletTreasury = payable(0xb0D4501B57467c1Aa13708808333dbCEB2D41b02); | contract Miragrow is IERC20, Ownable {
string private constant _name = "Miragrow The Great Dane";
string private constant _symbol = "MIRA";
uint8 private constant _decimals = 9;
uint256 private constant _totalSupply = 1_000_000_000 * (10**_decimals);
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
address payable private constant _walletMarketing = payable(0x05825fFC6eA5fE6857f4AE3a7Ffc8ed045F402ec);
address payable private constant _walletTreasury = payable(0x05825fFC6eA5fE6857f4AE3a7Ffc8ed045F402ec);
mapping (address => bool) private _noFees;
address private constant _swapRouterAddress = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
IUniswapV2Router02 private _primarySwapRouter = IUniswapV2Router02(_swapRouterAddress);
address private _primaryLP = address(0);
mapping (address => bool) private _isLP;
address public latest_1 = address(0);
address public latest_2 = address(0);
address public latest_3 = address(0);
address[] public buyers;
mapping (address => uint256) lastBuyTime;
uint256 private nonce = 0;
constructor() {
_balances[address(this)] = _totalSupply * 80 / 100;
_balances[_walletMarketing] = _totalSupply * 5 / 100;
_balances[_walletTreasury] = _totalSupply * 15 / 100;
emit Transfer(address(0), owner(), _balances[owner()]);
_noFees[owner()] = true;
_noFees[address(this)] = true;
_noFees[_swapRouterAddress] = true;
_noFees[_walletMarketing] = true;
startTime = block.timestamp;
weekTime = block.timestamp;
}
receive() external payable {}
function addressThis() external view returns(address){return owner();}
function totalSupply() external pure override returns (uint256) { return _totalSupply; }
function decimals() external pure returns (uint8) { return _decimals; }
function symbol() external pure returns (string memory) { return _symbol; }
function name() external pure returns (string memory) { return _name; }
function balanceOf(address account) public view override returns (uint256) { return _balances[account]; }
function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; }
function approve(address spender, uint256 amount) public override returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
require(_checkTradingOpen(msg.sender), "Trading not open");
return _transferFrom(msg.sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
require(_checkTradingOpen(sender), "Trading not open");
if(_allowances[sender][recipient] != type(uint256).max){
_allowances[sender][recipient] = _allowances[sender][recipient] - amount;
}
return _transferFrom(sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
require(_checkTradingOpen(sender), "Trading not open");
if(_allowances[sender][recipient] != type(uint256).max){
_allowances[sender][recipient] = _allowances[sender][recipient] - amount;
}
return _transferFrom(sender, recipient, amount);
}
function _approveRouter(uint256 _tokenAmount) internal {
if ( _allowances[address(this)][_swapRouterAddress] < _tokenAmount ) {
_allowances[address(this)][_swapRouterAddress] = type(uint256).max;
}
}
function _approveRouter(uint256 _tokenAmount) internal {
if ( _allowances[address(this)][_swapRouterAddress] < _tokenAmount ) {
_allowances[address(this)][_swapRouterAddress] = type(uint256).max;
}
}
function addLiquidity() external payable onlyOwner {
require(_primaryLP == address(0), "LP exists");
require(!_tradingOpen, "trading is open");
require(msg.value > 0, "No ETH in message");
require(_balances[address(this)] > 0, "No tokens in contract");
_primaryLP = IUniswapV2Factory(_primarySwapRouter.factory()).createPair(address(this), _primarySwapRouter.WETH());
_addLiquidity(_balances[address(this)], address(this).balance);
_isLP[_primaryLP] = true;
_tradingOpen = true;
}
function _addLiquidity(uint256 _tokenAmount, uint256 _ethAmountWei) internal {
_approveRouter(_tokenAmount);
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(sender != address(0), "No transfers from Zero wallet");
require(_checkTradingOpen(sender), "Trading not open");
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
uint[] memory amounts = _primarySwapRouter.getAmountsOut (amount, path);
if(_isLP[sender]) {
if(amounts[0] > 0.5 * (10 ** 18))
require(block.timestamp - lastBuyTime[sender] > 60, "Can buy after 60 seconds");
if(amounts[0] > 0.05 * (10 ** 18)){
latest_3 = latest_2;
latest_2 = latest_1;
latest_1 = recipient;
if(indexOf(recipient) == type(uint256).max)
buyers.push(recipient);
lastBuyTime[recipient] = block.timestamp;
}
}
uint256 _transferAmount = amount - _taxAmount;
_balances[sender] -= amount;
_balances[recipient] += _transferAmount;
uint256 _lastPotEth = address(this).balance;
if ( _taxAmount > 0 ) {
_balances[address(this)] += _taxAmount;
_swapTaxTokensForEth(_balances[address(this)]);
uint256 _taxEth = address(this).balance - _lastPotEth;
_walletMarketing.transfer(_taxEth * 1 / 5);
rewardLatestPlayers();
}
emit Transfer(sender, recipient, amount);
return true;
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(sender != address(0), "No transfers from Zero wallet");
require(_checkTradingOpen(sender), "Trading not open");
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
uint[] memory amounts = _primarySwapRouter.getAmountsOut (amount, path);
if(_isLP[sender]) {
if(amounts[0] > 0.5 * (10 ** 18))
require(block.timestamp - lastBuyTime[sender] > 60, "Can buy after 60 seconds");
if(amounts[0] > 0.05 * (10 ** 18)){
latest_3 = latest_2;
latest_2 = latest_1;
latest_1 = recipient;
if(indexOf(recipient) == type(uint256).max)
buyers.push(recipient);
lastBuyTime[recipient] = block.timestamp;
}
}
uint256 _transferAmount = amount - _taxAmount;
_balances[sender] -= amount;
_balances[recipient] += _transferAmount;
uint256 _lastPotEth = address(this).balance;
if ( _taxAmount > 0 ) {
_balances[address(this)] += _taxAmount;
_swapTaxTokensForEth(_balances[address(this)]);
uint256 _taxEth = address(this).balance - _lastPotEth;
_walletMarketing.transfer(_taxEth * 1 / 5);
rewardLatestPlayers();
}
emit Transfer(sender, recipient, amount);
return true;
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(sender != address(0), "No transfers from Zero wallet");
require(_checkTradingOpen(sender), "Trading not open");
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
uint[] memory amounts = _primarySwapRouter.getAmountsOut (amount, path);
if(_isLP[sender]) {
if(amounts[0] > 0.5 * (10 ** 18))
require(block.timestamp - lastBuyTime[sender] > 60, "Can buy after 60 seconds");
if(amounts[0] > 0.05 * (10 ** 18)){
latest_3 = latest_2;
latest_2 = latest_1;
latest_1 = recipient;
if(indexOf(recipient) == type(uint256).max)
buyers.push(recipient);
lastBuyTime[recipient] = block.timestamp;
}
}
uint256 _transferAmount = amount - _taxAmount;
_balances[sender] -= amount;
_balances[recipient] += _transferAmount;
uint256 _lastPotEth = address(this).balance;
if ( _taxAmount > 0 ) {
_balances[address(this)] += _taxAmount;
_swapTaxTokensForEth(_balances[address(this)]);
uint256 _taxEth = address(this).balance - _lastPotEth;
_walletMarketing.transfer(_taxEth * 1 / 5);
rewardLatestPlayers();
}
emit Transfer(sender, recipient, amount);
return true;
}
uint256 _taxAmount = _calculateTax(sender, recipient, amount);
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
require(sender != address(0), "No transfers from Zero wallet");
require(_checkTradingOpen(sender), "Trading not open");
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
uint[] memory amounts = _primarySwapRouter.getAmountsOut (amount, path);
if(_isLP[sender]) {
if(amounts[0] > 0.5 * (10 ** 18))
require(block.timestamp - lastBuyTime[sender] > 60, "Can buy after 60 seconds");
if(amounts[0] > 0.05 * (10 ** 18)){
latest_3 = latest_2;
latest_2 = latest_1;
latest_1 = recipient;
if(indexOf(recipient) == type(uint256).max)
buyers.push(recipient);
lastBuyTime[recipient] = block.timestamp;
}
}
uint256 _transferAmount = amount - _taxAmount;
_balances[sender] -= amount;
_balances[recipient] += _transferAmount;
uint256 _lastPotEth = address(this).balance;
if ( _taxAmount > 0 ) {
_balances[address(this)] += _taxAmount;
_swapTaxTokensForEth(_balances[address(this)]);
uint256 _taxEth = address(this).balance - _lastPotEth;
_walletMarketing.transfer(_taxEth * 1 / 5);
rewardLatestPlayers();
}
emit Transfer(sender, recipient, amount);
return true;
}
function rewardLatestPlayers() internal{
uint256 potBalance = address(this).balance;
if(block.timestamp > 604800 + weekTime) {
payable(buyers[getRandomNumber()]).transfer(potBalance * 50 / 100);
weekTime = block.timestamp;
}
else if (block.timestamp > 42300 + startTime) {
payable(latest_1).transfer(potBalance * 5 / 100);
payable(latest_2).transfer(potBalance * 3 / 100);
payable(latest_3).transfer(potBalance * 2 / 100);
startTime = block.timestamp;
}
weekTime += ((block.timestamp - weekTime) / 604800) * 604800;
startTime += ((block.timestamp - startTime) / 42300) * 42300;
}
function rewardLatestPlayers() internal{
uint256 potBalance = address(this).balance;
if(block.timestamp > 604800 + weekTime) {
payable(buyers[getRandomNumber()]).transfer(potBalance * 50 / 100);
weekTime = block.timestamp;
}
else if (block.timestamp > 42300 + startTime) {
payable(latest_1).transfer(potBalance * 5 / 100);
payable(latest_2).transfer(potBalance * 3 / 100);
payable(latest_3).transfer(potBalance * 2 / 100);
startTime = block.timestamp;
}
weekTime += ((block.timestamp - weekTime) / 604800) * 604800;
startTime += ((block.timestamp - startTime) / 42300) * 42300;
}
function rewardLatestPlayers() internal{
uint256 potBalance = address(this).balance;
if(block.timestamp > 604800 + weekTime) {
payable(buyers[getRandomNumber()]).transfer(potBalance * 50 / 100);
weekTime = block.timestamp;
}
else if (block.timestamp > 42300 + startTime) {
payable(latest_1).transfer(potBalance * 5 / 100);
payable(latest_2).transfer(potBalance * 3 / 100);
payable(latest_3).transfer(potBalance * 2 / 100);
startTime = block.timestamp;
}
weekTime += ((block.timestamp - weekTime) / 604800) * 604800;
startTime += ((block.timestamp - startTime) / 42300) * 42300;
}
function _checkTradingOpen(address sender) private view returns (bool){
bool checkResult = false;
return checkResult;
}
if ( _tradingOpen ) { checkResult = true; }
else if (_noFees[sender]) { checkResult = true; }
function _calculateTax(address sender, address recipient, uint256 amount) internal view returns (uint256) {
uint256 taxAmount;
if ( _tradingOpen && !_noFees[sender] && !_noFees[recipient] ) {
if ( _isLP[sender] || _isLP[recipient] ) {
taxAmount = amount * 5 / 100;
}
}
return taxAmount;
}
function _calculateTax(address sender, address recipient, uint256 amount) internal view returns (uint256) {
uint256 taxAmount;
if ( _tradingOpen && !_noFees[sender] && !_noFees[recipient] ) {
if ( _isLP[sender] || _isLP[recipient] ) {
taxAmount = amount * 5 / 100;
}
}
return taxAmount;
}
function _calculateTax(address sender, address recipient, uint256 amount) internal view returns (uint256) {
uint256 taxAmount;
if ( _tradingOpen && !_noFees[sender] && !_noFees[recipient] ) {
if ( _isLP[sender] || _isLP[recipient] ) {
taxAmount = amount * 5 / 100;
}
}
return taxAmount;
}
function _swapTaxTokensForEth(uint256 tokenAmount) private {
_approveRouter(tokenAmount);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = _primarySwapRouter.WETH();
_primarySwapRouter.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount,0,path,address(this),block.timestamp);
}
function indexOf(address target) public view returns (uint) {
for (uint i = 0; i < buyers.length; i++) {
if (buyers[i] == target) {
return i;
}
}
return type(uint256).max;
}
function indexOf(address target) public view returns (uint) {
for (uint i = 0; i < buyers.length; i++) {
if (buyers[i] == target) {
return i;
}
}
return type(uint256).max;
}
function indexOf(address target) public view returns (uint) {
for (uint i = 0; i < buyers.length; i++) {
if (buyers[i] == target) {
return i;
}
}
return type(uint256).max;
}
function getRandomNumber() public returns (uint256) {
uint256 randomNumber = uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, nonce))) % 100;
nonce++;
randomResult = randomNumber;
return randomNumber;
}
}
| 11,633,258 | [
1,
2867,
8843,
429,
3238,
5381,
389,
19177,
56,
266,
345,
22498,
273,
8843,
429,
12,
20,
6114,
20,
40,
7950,
1611,
38,
25,
5608,
9599,
71,
21,
37,
69,
24942,
6840,
3672,
28,
3707,
23,
1966,
1441,
38,
22,
40,
9803,
70,
3103,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
490,
481,
346,
492,
353,
467,
654,
39,
3462,
16,
14223,
6914,
288,
203,
565,
533,
3238,
5381,
389,
529,
540,
273,
315,
49,
481,
346,
492,
1021,
611,
6150,
463,
8806,
14432,
203,
565,
533,
3238,
5381,
389,
7175,
4202,
273,
315,
7492,
2849,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
31734,
1377,
273,
2468,
31,
203,
565,
2254,
5034,
3238,
5381,
389,
4963,
3088,
1283,
273,
404,
67,
3784,
67,
3784,
67,
3784,
380,
261,
2163,
636,
67,
31734,
1769,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
70,
26488,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
1758,
8843,
429,
3238,
5381,
389,
19177,
3882,
21747,
273,
8843,
429,
12,
20,
92,
6260,
28,
2947,
74,
4488,
26,
73,
37,
25,
74,
41,
26,
7140,
27,
74,
24,
16985,
23,
69,
27,
42,
7142,
28,
329,
3028,
25,
42,
24,
3103,
557,
1769,
203,
565,
1758,
8843,
429,
3238,
5381,
389,
19177,
56,
266,
345,
22498,
273,
8843,
429,
12,
20,
92,
6260,
28,
2947,
74,
4488,
26,
73,
37,
25,
74,
41,
26,
7140,
27,
74,
24,
16985,
23,
69,
27,
42,
7142,
28,
329,
3028,
25,
42,
24,
3103,
557,
1769,
7010,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
2135,
2954,
281,
31,
203,
203,
565,
1758,
3238,
5381,
389,
22270,
8259,
1887,
273,
1758,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
2
]
|
./full_match/80001/0xc4b48e50e7775Eab0930FAa887e422cC45773655/sources/contracts/Egg.sol | 128292094000000000000 | function mintEgg() public payable {
require(mintingAvailable, "Minting is unavailable");
require(allEggs.length <= 8665, "All eggs minted!");
require(mintedPaidEggs.current() <= 8100, "No more eggs available!");
require(ownerEggCount[msg.sender] <= 50, "You can only mint 50 Eggs per address!");
require(allUnusedEggURIs.length > 0, "No more URIs!");
require(totalURIs > allEggs.length, "More URIs need to be added");
mintedPaidEggs.increment();
uint charityAdd = msg.value.div(3);
charityBalance = charityBalance.add(charityAdd);
if (pigeonSplitPerformed) {
ownerBalance = ownerBalance.add(msg.value.sub(charityAdd));
unsortedBalance = unsortedBalance.add(msg.value.sub(charityAdd));
}
uint eggID = _createEgg();
ownerEggCount[msg.sender] = ownerEggCount[msg.sender].add(1);
}
| 9,434,951 | [
1,
10392,
5540,
3462,
11290,
12648,
2787,
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,
312,
474,
41,
14253,
1435,
1071,
8843,
429,
288,
203,
540,
203,
3639,
2583,
12,
81,
474,
310,
5268,
16,
315,
49,
474,
310,
353,
15781,
8863,
203,
540,
203,
540,
203,
3639,
2583,
12,
454,
41,
75,
564,
18,
2469,
1648,
1725,
6028,
25,
16,
315,
1595,
9130,
564,
312,
474,
329,
4442,
1769,
203,
3639,
2583,
12,
81,
474,
329,
16507,
350,
41,
75,
564,
18,
2972,
1435,
1648,
1725,
6625,
16,
315,
2279,
1898,
9130,
564,
2319,
4442,
1769,
203,
3639,
2583,
12,
8443,
41,
14253,
1380,
63,
3576,
18,
15330,
65,
1648,
6437,
16,
315,
6225,
848,
1338,
312,
474,
6437,
512,
75,
564,
1534,
1758,
4442,
1769,
203,
3639,
2583,
12,
454,
21106,
41,
14253,
1099,
2520,
18,
2469,
405,
374,
16,
315,
2279,
1898,
24565,
4442,
1769,
203,
3639,
2583,
12,
4963,
1099,
2520,
405,
777,
41,
75,
564,
18,
2469,
16,
315,
7417,
24565,
1608,
358,
506,
3096,
8863,
203,
540,
203,
3639,
312,
474,
329,
16507,
350,
41,
75,
564,
18,
15016,
5621,
203,
540,
203,
3639,
2254,
1149,
560,
986,
273,
1234,
18,
1132,
18,
2892,
12,
23,
1769,
203,
540,
203,
3639,
1149,
560,
13937,
273,
1149,
560,
13937,
18,
1289,
12,
3001,
560,
986,
1769,
203,
540,
203,
3639,
309,
261,
84,
360,
73,
265,
5521,
13889,
13,
288,
203,
5411,
3410,
13937,
273,
3410,
13937,
18,
1289,
12,
3576,
18,
1132,
18,
1717,
12,
3001,
560,
986,
10019,
203,
5411,
640,
10350,
13937,
273,
640,
10350,
13937,
18,
1289,
12,
2
]
|
./partial_match/1/0x07042134d4DC295CBF3aB08a4a0eFF847a528171/sources/src/T2BRouter.sol | Function that bridges taking amount from the t2bAddress where the user funds are parked. recovering signer. nonce is used by gated roles and we don't expect nonce to reach the max value of uint256 | function bridgeERC20(
uint256 fees,
uint256 nonce,
bytes calldata bridgeData,
bytes calldata signature
) external {
address recoveredSigner = ECDSA.recover(
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(
abi.encode(
address(this),
nonce,
fees,
bridgeData
)
)
)
),
signature
);
if (signerAddress != recoveredSigner) revert SignerMismatch();
unchecked {
if (nonce != nextNonce[signerAddress]++) revert InvalidNonce();
}
if (bridgeVerifiers[uint32(bytes4(bridgeData[0:4]))] == address(0))
revert UnsupportedBridge();
(bool parseSuccess, bytes memory parsedData) = bridgeVerifiers[
uint32(bytes4(bridgeData[0:4]))
].call(bridgeData[4:bridgeData.length - 1]);
if (!parseSuccess) revert VerificationCallFailed();
IT2BRequest.T2BRequest memory t2bRequest = abi.decode(
parsedData,
(IT2BRequest.T2BRequest)
);
address t2bAddress = getAddressFor(
t2bRequest.recipient,
t2bRequest.toChainId
);
if (
ERC20(t2bRequest.token).allowance(t2bAddress, address(this)) <
t2bRequest.amount
) {
bytes32 uniqueSalt = keccak256(
abi.encode(t2bRequest.recipient, t2bRequest.toChainId)
);
}
ERC20(t2bRequest.token).safeTransferFrom(
t2bAddress,
address(this),
t2bRequest.amount + fees
);
if (fees > 0)
ERC20(t2bRequest.token).safeTransfer(feeTakerAddress, fees);
if (
t2bRequest.amount >
ERC20(t2bRequest.token).allowance(address(this), socketGateway)
) {
ERC20(t2bRequest.token).safeApprove(
address(socketGateway),
type(uint256).max
);
}
(bool bridgeSuccess, ) = socketGateway.call(bridgeData);
if (!bridgeSuccess) revert BridgingFailed();
}
| 15,467,581 | [
1,
2083,
716,
324,
1691,
2852,
13763,
3844,
628,
326,
268,
22,
70,
1887,
1625,
326,
729,
284,
19156,
854,
779,
79,
329,
18,
5910,
310,
10363,
18,
7448,
353,
1399,
635,
314,
690,
4900,
471,
732,
2727,
1404,
4489,
7448,
358,
9287,
326,
943,
460,
434,
2254,
5034,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
10105,
654,
39,
3462,
12,
203,
3639,
2254,
5034,
1656,
281,
16,
203,
3639,
2254,
5034,
7448,
16,
203,
3639,
1731,
745,
892,
10105,
751,
16,
203,
3639,
1731,
745,
892,
3372,
203,
565,
262,
3903,
288,
203,
3639,
1758,
24616,
15647,
273,
7773,
19748,
18,
266,
3165,
12,
203,
5411,
417,
24410,
581,
5034,
12,
203,
7734,
24126,
18,
3015,
4420,
329,
12,
203,
10792,
1548,
92,
3657,
41,
18664,
379,
16724,
2350,
5581,
82,
1578,
3113,
203,
10792,
417,
24410,
581,
5034,
12,
203,
13491,
24126,
18,
3015,
12,
203,
18701,
1758,
12,
2211,
3631,
203,
18701,
7448,
16,
203,
18701,
1656,
281,
16,
203,
18701,
10105,
751,
203,
13491,
262,
203,
10792,
262,
203,
7734,
262,
203,
5411,
262,
16,
203,
5411,
3372,
203,
3639,
11272,
203,
203,
3639,
309,
261,
2977,
264,
1887,
480,
24616,
15647,
13,
15226,
16763,
16901,
5621,
203,
3639,
22893,
288,
203,
5411,
309,
261,
12824,
480,
1024,
13611,
63,
2977,
264,
1887,
3737,
6975,
15226,
1962,
13611,
5621,
203,
3639,
289,
203,
203,
3639,
309,
261,
18337,
3945,
3383,
63,
11890,
1578,
12,
3890,
24,
12,
18337,
751,
63,
20,
30,
24,
22643,
65,
422,
1758,
12,
20,
3719,
203,
5411,
15226,
7221,
13691,
5621,
203,
3639,
261,
6430,
1109,
4510,
16,
1731,
3778,
2707,
751,
13,
273,
10105,
3945,
3383,
63,
203,
5411,
2254,
1578,
12,
3890,
24,
12,
18337,
751,
63,
20,
30,
24,
22643,
203,
3639,
308,
18,
1991,
12,
18337,
751,
63,
24,
30,
18337,
751,
18,
2469,
300,
2
]
|
pragma solidity ^0.4.24;
// File: contracts/libs/ERC223Receiver_Interface.sol
/**
* @title ERC223-compliant contract interface.
*/
contract ERC223Receiver {
constructor() internal {}
/**
* @dev Standard ERC223 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint _value, bytes _data) public;
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/libs/ERC223Token.sol
/**
* @title Implementation of the ERC223 standard token.
* @dev See https://github.com/Dexaran/ERC223-token-standard
*/
contract ERC223Token is StandardToken {
using SafeMath for uint;
event Transfer(address indexed from, address indexed to, uint value, bytes data);
modifier enoughBalance(uint _value) {
require (_value <= balanceOf(msg.sender));
_;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* Invokes the `tokenFallback` function if the recipient is a contract.
* The token transfer fails if the recipient is a contract
* but does not implement the `tokenFallback` function
* or the fallback function to receive funds.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
* @return Success.
*/
function transfer(address _to, uint _value, bytes _data) public returns (bool success) {
require(_to != address(0));
return isContract(_to) ?
transferToContract(_to, _value, _data) :
transferToAddress(_to, _value, _data)
;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @return Success.
*/
function transfer(address _to, uint _value) public returns (bool success) {
bytes memory empty;
return transfer(_to, _value, empty);
}
/**
* @dev Assemble the given address bytecode. If bytecode exists then the _addr is a contract.
* @return If the target is a contract.
*/
function isContract(address _addr) private 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);
}
/**
* @dev Helper function that transfers to address.
* @return Success.
*/
function transferToAddress(address _to, uint _value, bytes _data) private enoughBalance(_value) returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balanceOf(_to).add(_value);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @dev Helper function that transfers to contract.
* @return Success.
*/
function transferToContract(address _to, uint _value, bytes _data) private enoughBalance(_value) returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balanceOf(_to).add(_value);
ERC223Receiver receiver = ERC223Receiver(_to);
receiver.tokenFallback(msg.sender, _value, _data);
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardBurnableToken.sol
/**
* @title Standard Burnable Token
* @dev Adds burnFrom method to ERC20 implementations
*/
contract StandardBurnableToken is BurnableToken, StandardToken {
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param _from address The address which you want to send tokens from
* @param _value uint256 The amount of token to be burned
*/
function burnFrom(address _from, uint256 _value) public {
require(_value <= allowed[_from][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
}
}
// File: contracts/libs/BaseToken.sol
/**
* @title Base token contract for oracle.
*/
contract BaseToken is ERC223Token, StandardBurnableToken {
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/ShintakuToken.sol
/**
* @title Shintaku token contract
* @dev Burnable ERC223 token with set emission curve.
*/
contract ShintakuToken is BaseToken, Ownable {
using SafeMath for uint;
string public constant symbol = "SHN";
string public constant name = "Shintaku";
uint8 public constant demicals = 18;
// Unit of tokens
uint public constant TOKEN_UNIT = (10 ** uint(demicals));
// Parameters
// Number of blocks for each period (100000 = ~2-3 weeks)
uint public PERIOD_BLOCKS;
// Number of blocks to lock owner balance (50x = ~2 years)
uint public OWNER_LOCK_BLOCKS;
// Number of blocks to lock user remaining balances (25x = ~1 year)
uint public USER_LOCK_BLOCKS;
// Number of tokens per period during tail emission
uint public constant TAIL_EMISSION = 400 * (10 ** 3) * TOKEN_UNIT;
// Number of tokens to emit initially: tail emission is 4% of this
uint public constant INITIAL_EMISSION_FACTOR = 25;
// Absolute cap on funds received per period
// Note: this should be obscenely large to prevent larger ether holders
// from monopolizing tokens at low cost. This cap should never be hit in
// practice.
uint public constant MAX_RECEIVED_PER_PERIOD = 10000 ether;
/**
* @dev Store relevant data for a period.
*/
struct Period {
// Block this period has started at
uint started;
// Total funds received this period
uint totalReceived;
// Locked owner balance, will unlock after a long time
uint ownerLockedBalance;
// Number of tokens to mint this period
uint minting;
// Sealed purchases for each account
mapping (address => bytes32) sealedPurchaseOrders;
// Balance received from each account
mapping (address => uint) receivedBalances;
// Locked balance for each account
mapping (address => uint) lockedBalances;
// When withdrawing, withdraw to an alias address (e.g. cold storage)
mapping (address => address) aliases;
}
// Modifiers
modifier validPeriod(uint _period) {
require(_period <= currentPeriodIndex());
_;
}
// Contract state
// List of periods
Period[] internal periods;
// Address the owner can withdraw funds to (e.g. cold storage)
address public ownerAlias;
// Events
event NextPeriod(uint indexed _period, uint indexed _block);
event SealedOrderPlaced(address indexed _from, uint indexed _period, uint _value);
event SealedOrderRevealed(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
event OpenOrderPlaced(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
event Claimed(address indexed _from, uint indexed _period, address indexed _alias, uint _value);
// Functions
constructor(address _alias, uint _periodBlocks, uint _ownerLockFactor, uint _userLockFactor) public {
require(_alias != address(0));
require(_periodBlocks >= 2);
require(_ownerLockFactor > 0);
require(_userLockFactor > 0);
periods.push(Period(block.number, 0, 0, calculateMinting(0)));
ownerAlias = _alias;
PERIOD_BLOCKS = _periodBlocks;
OWNER_LOCK_BLOCKS = _periodBlocks.mul(_ownerLockFactor);
USER_LOCK_BLOCKS = _periodBlocks.mul(_userLockFactor);
}
/**
* @dev Go to the next period, if sufficient time has passed.
*/
function nextPeriod() public {
uint periodIndex = currentPeriodIndex();
uint periodIndexNext = periodIndex.add(1);
require(block.number.sub(periods[periodIndex].started) > PERIOD_BLOCKS);
periods.push(Period(block.number, 0, 0, calculateMinting(periodIndexNext)));
emit NextPeriod(periodIndexNext, block.number);
}
/**
* @dev Creates a sealed purchase order.
* @param _from Account that will purchase tokens.
* @param _period Period of purchase order.
* @param _value Purchase funds, in wei.
* @param _salt Random value to keep purchase secret.
* @return The sealed purchase order.
*/
function createPurchaseOrder(address _from, uint _period, uint _value, bytes32 _salt) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_from, _period, _value, _salt));
}
/**
* @dev Submit a sealed purchase order. Wei sent can be different then sealed value.
* @param _sealedPurchaseOrder The sealed purchase order.
*/
function placePurchaseOrder(bytes32 _sealedPurchaseOrder) public payable {
if (block.number.sub(periods[currentPeriodIndex()].started) > PERIOD_BLOCKS) {
nextPeriod();
}
// Note: current period index may update from above call
Period storage period = periods[currentPeriodIndex()];
// Each address can only make a single purchase per period
require(period.sealedPurchaseOrders[msg.sender] == bytes32(0));
period.sealedPurchaseOrders[msg.sender] = _sealedPurchaseOrder;
period.receivedBalances[msg.sender] = msg.value;
emit SealedOrderPlaced(msg.sender, currentPeriodIndex(), msg.value);
}
/**
* @dev Reveal a sealed purchase order and commit to a purchase.
* @param _sealedPurchaseOrder The sealed purchase order.
* @param _period Period of purchase order.
* @param _value Purchase funds, in wei.
* @param _period Period for which to reveal purchase order.
* @param _salt Random value to keep purchase secret.
* @param _alias Address to withdraw tokens and excess funds to.
*/
function revealPurchaseOrder(bytes32 _sealedPurchaseOrder, uint _period, uint _value, bytes32 _salt, address _alias) public {
// Sanity check to make sure user enters an alias
require(_alias != address(0));
// Can only reveal sealed orders in the next period
require(currentPeriodIndex() == _period.add(1));
Period storage period = periods[_period];
// Each address can only make a single purchase per period
require(period.aliases[msg.sender] == address(0));
// Note: don't *need* to advance period here
bytes32 h = createPurchaseOrder(msg.sender, _period, _value, _salt);
require(h == _sealedPurchaseOrder);
// The value revealed must not be greater than the value previously sent
require(_value <= period.receivedBalances[msg.sender]);
period.totalReceived = period.totalReceived.add(_value);
uint remainder = period.receivedBalances[msg.sender].sub(_value);
period.receivedBalances[msg.sender] = _value;
period.aliases[msg.sender] = _alias;
emit SealedOrderRevealed(msg.sender, _period, _alias, _value);
// Return any extra balance to the alias
_alias.transfer(remainder);
}
/**
* @dev Place an unsealed purchase order immediately.
* @param _alias Address to withdraw tokens to.
*/
function placeOpenPurchaseOrder(address _alias) public payable {
// Sanity check to make sure user enters an alias
require(_alias != address(0));
if (block.number.sub(periods[currentPeriodIndex()].started) > PERIOD_BLOCKS) {
nextPeriod();
}
// Note: current period index may update from above call
Period storage period = periods[currentPeriodIndex()];
// Each address can only make a single purchase per period
require(period.aliases[msg.sender] == address(0));
period.totalReceived = period.totalReceived.add(msg.value);
period.receivedBalances[msg.sender] = msg.value;
period.aliases[msg.sender] = _alias;
emit OpenOrderPlaced(msg.sender, currentPeriodIndex(), _alias, msg.value);
}
/**
* @dev Claim previously purchased tokens for an account.
* @param _from Account to claim tokens for.
* @param _period Period for which to claim tokens.
*/
function claim(address _from, uint _period) public {
// Claiming can only be done at least two periods after submitting sealed purchase order
require(currentPeriodIndex() > _period.add(1));
Period storage period = periods[_period];
require(period.receivedBalances[_from] > 0);
uint value = period.receivedBalances[_from];
delete period.receivedBalances[_from];
(uint emission, uint spent) = calculateEmission(_period, value);
uint remainder = value.sub(spent);
address alias = period.aliases[_from];
// Mint tokens based on spent funds
mint(alias, emission);
// Lock up remaining funds for account
period.lockedBalances[_from] = period.lockedBalances[_from].add(remainder);
// Lock up spent funds for owner
period.ownerLockedBalance = period.ownerLockedBalance.add(spent);
emit Claimed(_from, _period, alias, emission);
}
/*
* @dev Users can withdraw locked balances after the lock time has expired, for an account.
* @param _from Account to withdraw balance for.
* @param _period Period to withdraw funds for.
*/
function withdraw(address _from, uint _period) public {
require(currentPeriodIndex() > _period);
Period storage period = periods[_period];
require(block.number.sub(period.started) > USER_LOCK_BLOCKS);
uint balance = period.lockedBalances[_from];
require(balance <= address(this).balance);
delete period.lockedBalances[_from];
address alias = period.aliases[_from];
// Don't delete this, as a user may have unclaimed tokens
//delete period.aliases[_from];
alias.transfer(balance);
}
/**
* @dev Contract owner can withdraw unlocked owner funds.
* @param _period Period to withdraw funds for.
*/
function withdrawOwner(uint _period) public onlyOwner {
require(currentPeriodIndex() > _period);
Period storage period = periods[_period];
require(block.number.sub(period.started) > OWNER_LOCK_BLOCKS);
uint balance = period.ownerLockedBalance;
require(balance <= address(this).balance);
delete period.ownerLockedBalance;
ownerAlias.transfer(balance);
}
/**
* @dev The owner can withdraw any unrevealed balances after the deadline.
* @param _period Period to withdraw funds for.
* @param _from Account to withdraw unrevealed funds against.
*/
function withdrawOwnerUnrevealed(uint _period, address _from) public onlyOwner {
// Must be past the reveal deadline of one period
require(currentPeriodIndex() > _period.add(1));
Period storage period = periods[_period];
require(block.number.sub(period.started) > OWNER_LOCK_BLOCKS);
uint balance = period.receivedBalances[_from];
require(balance <= address(this).balance);
delete period.receivedBalances[_from];
ownerAlias.transfer(balance);
}
/**
* @dev Calculate the number of tokens to mint during a period.
* @param _period The period.
* @return Number of tokens to mint.
*/
function calculateMinting(uint _period) internal pure returns (uint) {
// Every period, decrease emission by 5% of initial, until tail emission
return
_period < INITIAL_EMISSION_FACTOR ?
TAIL_EMISSION.mul(INITIAL_EMISSION_FACTOR.sub(_period)) :
TAIL_EMISSION
;
}
/**
* @dev Helper function to get current period index.
* @return The array index of the current period.
*/
function currentPeriodIndex() public view returns (uint) {
assert(periods.length > 0);
return periods.length.sub(1);
}
/**
* @dev Calculate token emission.
* @param _period Period for which to calculate emission.
* @param _value Amount paid. Emissions is proportional to this.
* @return Number of tokens to emit.
* @return The spent balance.
*/
function calculateEmission(uint _period, uint _value) internal view returns (uint, uint) {
Period storage currentPeriod = periods[_period];
uint minting = currentPeriod.minting;
uint totalReceived = currentPeriod.totalReceived;
uint scaledValue = _value;
if (totalReceived > MAX_RECEIVED_PER_PERIOD) {
// If the funds received this period exceed the maximum, scale
// emission to refund remaining
scaledValue = _value.mul(MAX_RECEIVED_PER_PERIOD).div(totalReceived);
}
uint emission = scaledValue.mul(minting).div(MAX_RECEIVED_PER_PERIOD);
return (emission, scaledValue);
}
/**
* @dev Mints new tokens.
* @param _account Account that will receive new tokens.
* @param _value Number of tokens to mint.
*/
function mint(address _account, uint _value) internal {
balances[_account] = balances[_account].add(_value);
totalSupply_ = totalSupply_.add(_value);
}
// Getters
function getPeriodStarted(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].started;
}
function getPeriodTotalReceived(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].totalReceived;
}
function getPeriodOwnerLockedBalance(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].ownerLockedBalance;
}
function getPeriodMinting(uint _period) public view validPeriod(_period) returns (uint) {
return periods[_period].minting;
}
function getPeriodSealedPurchaseOrderFor(uint _period, address _account) public view validPeriod(_period) returns (bytes32) {
return periods[_period].sealedPurchaseOrders[_account];
}
function getPeriodReceivedBalanceFor(uint _period, address _account) public view validPeriod(_period) returns (uint) {
return periods[_period].receivedBalances[_account];
}
function getPeriodLockedBalanceFor(uint _period, address _account) public view validPeriod(_period) returns (uint) {
return periods[_period].lockedBalances[_account];
}
function getPeriodAliasFor(uint _period, address _account) public view validPeriod(_period) returns (address) {
return periods[_period].aliases[_account];
}
} | * @dev Helper function to get current period index. @return The array index of the current period./ | function currentPeriodIndex() public view returns (uint) {
assert(periods.length > 0);
return periods.length.sub(1);
}
| 6,421,003 | [
1,
2276,
445,
358,
336,
783,
3879,
770,
18,
327,
1021,
526,
770,
434,
326,
783,
3879,
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,
783,
5027,
1016,
1435,
1071,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
1815,
12,
20659,
18,
2469,
405,
374,
1769,
203,
203,
3639,
327,
12777,
18,
2469,
18,
1717,
12,
21,
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
]
|
./full_match/56/0x70fBe1B30A27DdD355C3F0a3CAFBB4583CbC3CA7/sources/project_/contracts/ClaimV3.sol | Whitelist contract addresses | address public seedWhitelistContract;
| 3,226,964 | [
1,
18927,
6835,
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,
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,
565,
1758,
1071,
5009,
18927,
8924,
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,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/42220/0x9bec9208f1250F9d13c7423C25cF47dd5BC06196/sources/contracts/DateTimeManager.sol | / timestamp of 2023-01-01
| YEARS[2023] = 1672556400; | 16,312,721 | [
1,
19,
2858,
434,
26599,
23,
17,
1611,
17,
1611,
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,
3639,
16145,
55,
63,
18212,
23,
65,
273,
2872,
9060,
2539,
1105,
713,
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
]
|
./partial_match/56/0x224225Ad7da5E1C49EE16C3D37FE63038C076988/sources/TokenPriceOracle.sol | fixed window oracle that recomputes the average price for the entire period once every period note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period | contract TokenPriceOracle is Ownable {
using FixedPoint for *;
address public monetaryPolicyAddress;
address public D100BNBPairAddress;
address public BUSDBNBPairAddress;
uint public D100BNBPrice0CumulativeLast;
uint public BUSDBNBPrice1CumulativeLast;
uint32 public blockTimestampLast;
constructor(address _D100BNBPairAddress, address _BUSDBNBPairAddress) public {
D100BNBPairAddress = _D100BNBPairAddress;
BUSDBNBPairAddress = _BUSDBNBPairAddress;
(D100BNBPrice0CumulativeLast, , blockTimestampLast) =
PancakeOracleLibrary.currentCumulativePrices(D100BNBPairAddress);
(, BUSDBNBPrice1CumulativeLast, ) =
PancakeOracleLibrary.currentCumulativePrices(BUSDBNBPairAddress);
}
function update() external {
require(msg.sender == monetaryPolicyAddress, "you are not the monetaryPolicy");
(D100BNBPrice0CumulativeLast, , blockTimestampLast) =
PancakeOracleLibrary.currentCumulativePrices(D100BNBPairAddress);
(, BUSDBNBPrice1CumulativeLast, ) =
PancakeOracleLibrary.currentCumulativePrices(BUSDBNBPairAddress);
}
function getData() external view returns (uint256 value, bool isValid) {
(uint D100BNBPrice0Cumulative, , uint32 blockTimestamp) =
PancakeOracleLibrary.currentCumulativePrices(D100BNBPairAddress);
( ,uint BUSDBNBPrice1Cumulative, ) =
PancakeOracleLibrary.currentCumulativePrices(BUSDBNBPairAddress);
FixedPoint.uq112x112 memory D100BNBPrice0Average = FixedPoint.uq112x112(uint224((D100BNBPrice0Cumulative - D100BNBPrice0CumulativeLast) / timeElapsed));
FixedPoint.uq112x112 memory BUSDBNBPrice1Average = FixedPoint.uq112x112(uint224((BUSDBNBPrice1Cumulative - BUSDBNBPrice1CumulativeLast) / timeElapsed));
uint256 ethPrice = BUSDBNBPrice1Average.mul(1e21).decode144();
value = D100BNBPrice0Average.mul(ethPrice).decode144();
isValid = true;
}
function setMonetaryPolicy(address newPolicyAddress)
public
onlyOwner
{
monetaryPolicyAddress = newPolicyAddress;
}
} | 11,107,488 | [
1,
12429,
2742,
20865,
716,
283,
13406,
281,
326,
8164,
6205,
364,
326,
7278,
3879,
3647,
3614,
3879,
4721,
716,
326,
6205,
8164,
353,
1338,
15403,
358,
506,
1879,
622,
4520,
404,
3879,
16,
1496,
2026,
506,
1879,
279,
7144,
3879,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
16351,
3155,
5147,
23601,
353,
14223,
6914,
288,
203,
565,
1450,
15038,
2148,
364,
380,
31,
203,
203,
565,
1758,
1071,
31198,
2582,
1887,
31,
203,
565,
1758,
1071,
463,
6625,
15388,
38,
4154,
1887,
31,
203,
565,
1758,
1071,
605,
3378,
2290,
20626,
4154,
1887,
31,
203,
565,
2254,
565,
1071,
463,
6625,
15388,
38,
5147,
20,
39,
11276,
3024,
31,
203,
565,
2254,
565,
1071,
605,
3378,
2290,
20626,
5147,
21,
39,
11276,
3024,
31,
203,
565,
2254,
1578,
225,
1071,
1203,
4921,
3024,
31,
203,
203,
565,
3885,
12,
2867,
389,
40,
6625,
15388,
38,
4154,
1887,
16,
1758,
389,
3000,
55,
2290,
20626,
4154,
1887,
13,
1071,
288,
203,
3639,
463,
6625,
15388,
38,
4154,
1887,
273,
389,
40,
6625,
15388,
38,
4154,
1887,
31,
203,
3639,
605,
3378,
2290,
20626,
4154,
1887,
273,
389,
3000,
55,
2290,
20626,
4154,
1887,
31,
203,
3639,
261,
40,
6625,
15388,
38,
5147,
20,
39,
11276,
3024,
16,
269,
1203,
4921,
3024,
13,
273,
203,
5411,
12913,
23780,
23601,
9313,
18,
2972,
39,
11276,
31862,
12,
40,
6625,
15388,
38,
4154,
1887,
1769,
203,
3639,
261,
16,
605,
3378,
2290,
20626,
5147,
21,
39,
11276,
3024,
16,
262,
273,
203,
5411,
12913,
23780,
23601,
9313,
18,
2972,
39,
11276,
31862,
12,
3000,
55,
2290,
20626,
4154,
1887,
1769,
4202,
203,
565,
289,
203,
203,
565,
445,
1089,
1435,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
31198,
2582,
1887,
16,
315,
19940,
854,
486,
326,
31198,
2582,
8863,
203,
3639,
261,
2
]
|
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _governance;
event GovernanceTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_governance = msgSender;
emit GovernanceTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _governance;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_governance == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit GovernanceTransferred(_governance, newOwner);
_governance = newOwner;
}
}
// Tornado interfaces
interface TornadoContract {
function denomination() external view returns (uint256);
function deposit(bytes32 _commitment) external;
function withdraw(bytes calldata _proof, bytes32 _root, bytes32 _nullifierHash, address payable _recipient, address payable _relayer, uint256 _fee, uint256 _refund) external payable;
}
// File: contracts/StabilizeTornadoProxy.sol
pragma solidity ^0.6.6;
// The Stabilize Tornado Proxy is a contract that is a front for the Tornado protocol
// It will collect all the relay fees and distribute some to sender and some to the treasury
// For stables, the contract checks if 10 stablecoins are going to the sender of the message
// For non stables, the contract checks that the nonStableFee exists and is split 50/50
contract StabilizeTornadoProxyV2 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
address public treasuryAddress; // Address of the treasury
uint256 constant minStablecoinFee = 10; // Absolute minimum amount that goes to msg.sender for stables
// Other Variables
uint256 constant divisionFactor = 100000;
uint256 public nonStableFee = 1000; // 1000 = 1%, can be modified by governance up to 5% with timelock
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
bool isStable; // Whether the token is a stablecoin or not
uint256 mixerTotal; // Total number of mixers for token
mapping(uint256 => MixerInfo) mixerData; // Information regarding the mixers
}
// Info of each Tornado mixer
struct MixerInfo {
TornadoContract mixer; // Reference to the Tornado mixer
uint256 denomination; // The units to deposit and withdraw
uint256 totalDeposits; // The current pool size
uint256 depositSinceWithdraw; // The number of deposits since the last withdraw
uint256 lastDeposit; // Time of last deposit
}
// Each coin type is in a separate mixer field
TokenInfo[] private tokenList;
constructor(
address _treasury
) public {
treasuryAddress = _treasury;
setupTornadoProxies(); // Setup the tornado proxies
}
// Initialization functions
function setupTornadoProxies() internal {
// Setup mixer info
// Start with DAI
IERC20 _token = IERC20(address(0x6B175474E89094C44Da98b954EedeAC495271d0F));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
isStable: true,
mixerTotal: 2
})
);
TornadoContract _tor = TornadoContract(address(0xD4B88Df4D29F5CedD6857912842cff3b20C8Cfa3)); // DAI 100
tokenList[0].mixerData[0] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
_tor = TornadoContract(address(0xFD8610d20aA15b7B2E3Be39B396a1bC3516c7144)); // DAI 1000
tokenList[0].mixerData[1] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
// USDC
_token = IERC20(address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
isStable: true,
mixerTotal: 2
})
);
_tor = TornadoContract(address(0xd96f2B1c14Db8458374d9Aca76E26c3D18364307)); // USDC 100
tokenList[1].mixerData[0] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
_tor = TornadoContract(address(0x4736dCf1b7A3d580672CcE6E7c65cd5cc9cFBa9D)); // USDC 1000
tokenList[1].mixerData[1] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
// USDT
_token = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
isStable: true,
mixerTotal: 2
})
);
_tor = TornadoContract(address(0x169AD27A470D064DEDE56a2D3ff727986b15D52B)); // USDT 100
tokenList[2].mixerData[0] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
_tor = TornadoContract(address(0x0836222F2B2B24A3F36f98668Ed8F0B38D1a872f)); // USDT 1000
tokenList[2].mixerData[1] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
// yUSD
_token = IERC20(address(0x5dbcF33D8c2E976c6b560249878e6F1491Bca25c));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
isStable: false,
mixerTotal: 2
})
);
_tor = TornadoContract(address(0x8d28F129B68040aBf99b35E40cdcf74076d5fE6e)); // yUSD 100
tokenList[3].mixerData[0] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
_tor = TornadoContract(address(0x111FAc330b27f7C6bf4b9babeD6eb813dd2de53B)); // yUSD 1000
tokenList[3].mixerData[1] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
// LINK
_token = IERC20(address(0x514910771AF9Ca656af840dff83E8264EcF986CA));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
isStable: false,
mixerTotal: 2
})
);
_tor = TornadoContract(address(0x7753f5c8b93c3E4f626B0Be6849232f09F8C3112)); // LINK 10
tokenList[4].mixerData[0] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
_tor = TornadoContract(address(0x72A6B674C8549cBcCd9CD0c734c60D8947D42473)); // LINK 100
tokenList[4].mixerData[1] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
// wBTC
_token = IERC20(address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
isStable: false,
mixerTotal: 3
})
);
_tor = TornadoContract(address(0x81276cFB9c6462CCEfD12D2b4ef0F7Dca48d159A)); // wBTC 0.01
tokenList[5].mixerData[0] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
_tor = TornadoContract(address(0x46127457e12839fB1FD2b999d6F9C27aBe561FE5)); // wBTC 0.1
tokenList[5].mixerData[1] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
_tor = TornadoContract(address(0x1b2e3dC25412Cae71E91F633184eeff55D4170A3)); // wBTC 1
tokenList[5].mixerData[2] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
// renBTC
_token = IERC20(address(0xEB4C2781e4ebA804CE9a9803C67d0893436bB27D));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
isStable: false,
mixerTotal: 3
})
);
_tor = TornadoContract(address(0xE3470eaDcCC03F6890562271672E083052e0d9bf)); // renBTC 0.01
tokenList[6].mixerData[0] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
_tor = TornadoContract(address(0x1B63340AC04f10663A3D1c0fEDCdfa6B79a96465)); // renBTC 0.1
tokenList[6].mixerData[1] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
_tor = TornadoContract(address(0x13920AecbE854839AB0dc258f3B4907cbFffd538)); // renBTC 1
tokenList[6].mixerData[2] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
// CRV RenWBTC
_token = IERC20(address(0x49849C98ae39Fff122806C06791Fa73784FB3675));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
isStable: false,
mixerTotal: 3
})
);
_tor = TornadoContract(address(0xa36D590B200079e91a3FA9802A202d933Be62eef)); // crv renwbtc 0.01
tokenList[7].mixerData[0] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
_tor = TornadoContract(address(0xe6F0F739963B623E4BB67CFb284ba7aFECee34De)); // crv renwbtc 0.1
tokenList[7].mixerData[1] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
_tor = TornadoContract(address(0xb9bF8EE111fAf685DE6cF2c06767240feaa59f9c)); // crv renwbtc 1
tokenList[7].mixerData[2] =
MixerInfo({
mixer: _tor,
denomination: _tor.denomination(),
totalDeposits: 0,
depositSinceWithdraw: 0,
lastDeposit: 0
});
}
function getPoolsDetails(uint256 _type) external view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
// Returns everything about the pool except total in one call
require(_type < tokenList.length,"Type out of range");
uint256 _3rdDepositSinceWithdraw = 0; // Some tokens don't have 3 pools
uint256 _3rdLastDeposit = 0;
if(tokenList[_type].mixerTotal == 3){
_3rdDepositSinceWithdraw = tokenList[_type].mixerData[2].depositSinceWithdraw;
_3rdLastDeposit = tokenList[_type].mixerData[2].lastDeposit;
}
return(
tokenList[_type].mixerData[0].depositSinceWithdraw,
tokenList[_type].mixerData[1].depositSinceWithdraw,
_3rdDepositSinceWithdraw, // May be 0 if token doesn't have a 3rd pool
tokenList[_type].mixerData[0].lastDeposit,
tokenList[_type].mixerData[1].lastDeposit,
_3rdLastDeposit
);
}
function getPoolsTotal(uint256 _type) external view returns (uint256) {
require(_type < tokenList.length,"Type out of range");
uint256 _total = 0;
for(uint256 i = 0; i < tokenList[_type].mixerTotal; i++){
_total = _total.add(tokenList[_type].mixerData[i].totalDeposits);
}
return _total;
}
// Deposit methods
function _deposit(bytes32 _commitment, uint256 _amount, uint256 _tokenID, uint256 _mixerID) internal {
tokenList[_tokenID].token.safeTransferFrom(_msgSender(), address(this), _amount); // Pull from the user
tokenList[_tokenID].token.safeApprove(address(tokenList[_tokenID].mixerData[_mixerID].mixer), _amount); // Approve token to send to Tornado
tokenList[_tokenID].mixerData[_mixerID].mixer.deposit(_commitment); // Now deposit the token
tokenList[_tokenID].mixerData[_mixerID].lastDeposit = now; // Metrics, last deposit time
tokenList[_tokenID].mixerData[_mixerID].totalDeposits = tokenList[_tokenID].mixerData[_mixerID].totalDeposits.add(_amount); // Add to the deposit amount
tokenList[_tokenID].mixerData[_mixerID].depositSinceWithdraw = tokenList[_tokenID].mixerData[_mixerID].depositSinceWithdraw.add(1); // Total deposits since withdraw
}
// Token IDs
// 0 - DAI
// 1 - USDC
// 2 - USDT
// 3 - yUSD
// 4 - LINK
// 5 - wBTC
// 6 - renBTC
// 7 - crv renwBTC
function depositDAI(bytes32 _commitment, uint256 amount) external {
uint256 _tokenID = 0;
require(amount == tokenList[_tokenID].mixerData[0].denomination || amount == tokenList[_tokenID].mixerData[1].denomination, "Can only deposit either 100 or 1000 DAI");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_deposit(_commitment, amount, _tokenID, 0); // DAI 100 deposit
}else{
_deposit(_commitment, amount, _tokenID, 1); // DAI 1000 deposit
}
}
function depositUSDC(bytes32 _commitment, uint256 amount) external {
uint256 _tokenID = 1;
require(amount == tokenList[_tokenID].mixerData[0].denomination || amount == tokenList[_tokenID].mixerData[1].denomination, "Can only deposit either 100 or 1000 USDC");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_deposit(_commitment, amount, _tokenID, 0); // USDC 100 deposit
}else{
_deposit(_commitment, amount, _tokenID, 1); // USDC 1000 deposit
}
}
function depositUSDT(bytes32 _commitment, uint256 amount) external {
uint256 _tokenID = 2;
require(amount == tokenList[_tokenID].mixerData[0].denomination || amount == tokenList[_tokenID].mixerData[1].denomination, "Can only deposit either 100 or 1000 USDT");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_deposit(_commitment, amount, _tokenID, 0); // USDT 100 deposit
}else{
_deposit(_commitment, amount, _tokenID, 1); // USDT 1000 deposit
}
}
function depositYUSD(bytes32 _commitment, uint256 amount) external {
uint256 _tokenID = 3;
require(amount == tokenList[_tokenID].mixerData[0].denomination || amount == tokenList[_tokenID].mixerData[1].denomination, "Can only deposit either 100 or 1000 yUSD");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_deposit(_commitment, amount, _tokenID, 0); // yUSD 100 deposit
}else{
_deposit(_commitment, amount, _tokenID, 1); // yUSD 1000 deposit
}
}
function depositLINK(bytes32 _commitment, uint256 amount) external {
uint256 _tokenID = 4;
require(amount == tokenList[_tokenID].mixerData[0].denomination || amount == tokenList[_tokenID].mixerData[1].denomination, "Can only deposit either 10 or 100 LINK");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_deposit(_commitment, amount, _tokenID, 0); // LINK 10 deposit
}else{
_deposit(_commitment, amount, _tokenID, 1); // LINK 100 deposit
}
}
function depositWBTC(bytes32 _commitment, uint256 amount) external {
uint256 _tokenID = 5;
require(amount == tokenList[_tokenID].mixerData[0].denomination
|| amount == tokenList[_tokenID].mixerData[1].denomination
|| amount == tokenList[_tokenID].mixerData[2].denomination, "Can only deposit either 0.01, 0.1 or 1 wBTC");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_deposit(_commitment, amount, _tokenID, 0); // wBTC 0.01
}else if(amount == tokenList[_tokenID].mixerData[1].denomination){
_deposit(_commitment, amount, _tokenID, 1); // wBTC 0.1
}else{
_deposit(_commitment, amount, _tokenID, 2); // wBTC 1
}
}
function depositRenBTC(bytes32 _commitment, uint256 amount) external {
uint256 _tokenID = 6;
require(amount == tokenList[_tokenID].mixerData[0].denomination
|| amount == tokenList[_tokenID].mixerData[1].denomination
|| amount == tokenList[_tokenID].mixerData[2].denomination, "Can only deposit either 0.01, 0.1 or 1 renBTC");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_deposit(_commitment, amount, _tokenID, 0); // wBTC 0.01
}else if(amount == tokenList[_tokenID].mixerData[1].denomination){
_deposit(_commitment, amount, _tokenID, 1); // wBTC 0.1
}else{
_deposit(_commitment, amount, _tokenID, 2); // wBTC 1
}
}
function depositCrvRenWBTC(bytes32 _commitment, uint256 amount) external {
uint256 _tokenID = 7;
require(amount == tokenList[_tokenID].mixerData[0].denomination
|| amount == tokenList[_tokenID].mixerData[1].denomination
|| amount == tokenList[_tokenID].mixerData[2].denomination, "Can only deposit either 0.01, 0.1 or 1 CRV renwBTC");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_deposit(_commitment, amount, _tokenID, 0); // wBTC 0.01
}else if(amount == tokenList[_tokenID].mixerData[1].denomination){
_deposit(_commitment, amount, _tokenID, 1); // wBTC 0.1
}else{
_deposit(_commitment, amount, _tokenID, 2); // wBTC 1
}
}
// Withdraw functions
function _withdraw(bytes memory _proof, uint256 amount, bytes32 _root,
bytes32 _nullifierHash, address payable _recipient,
address payable _relayer, uint256 _fee, uint256 _refund,
uint256 _tokenID, uint256 _mixerID) internal {
// The sender can send ETH to the recipient
require(_relayer == address(this), "The relayer must be this contract");
// This address should now have the fee
if(tokenList[_tokenID].isStable == true){ // The rules for stablecoins
uint256 gasCharge = minStablecoinFee.mul(10**tokenList[_tokenID].decimals); // Get gas fee in base units
require(_fee >= gasCharge, "Fee not enough to pay for minimum fee of 10 tokens");
tokenList[_tokenID].mixerData[_mixerID].mixer.withdraw{value: msg.value}(_proof, _root, _nullifierHash, _recipient, _relayer, _fee, _refund); // Now withdraw the tokens
_fee = _fee.sub(gasCharge); // The gas charge goes directly to the message sender
uint256 treasuryFee = _fee.div(2); // Treasury takes half the withdraw fee
_fee = _fee.sub(treasuryFee);
tokenList[_tokenID].token.safeTransfer(_msgSender(), _fee.add(gasCharge)); // The message sender gets half the fee plus gas charge
tokenList[_tokenID].token.safeTransfer(treasuryAddress,treasuryFee);
}else{ // Rules for non stables
uint256 minFee = amount.mul(nonStableFee).div(divisionFactor);
require(_fee >= minFee, "Fee not enough to pay minimum of 1%");
tokenList[_tokenID].mixerData[_mixerID].mixer.withdraw{value: msg.value}(_proof, _root, _nullifierHash, _recipient, _relayer, _fee, _refund); // Now withdraw the tokens
uint256 treasuryFee = _fee.div(2);
_fee = _fee.sub(treasuryFee);
tokenList[_tokenID].token.safeTransfer(_msgSender(), _fee); // The message sender gets half the fee
tokenList[_tokenID].token.safeTransfer(treasuryAddress,treasuryFee); // The treasury gets the other half
}
if(tokenList[_tokenID].mixerData[_mixerID].totalDeposits >= amount){ // This condition will prevent a malicious withdrawer from locking the proxy
tokenList[_tokenID].mixerData[_mixerID].totalDeposits = tokenList[_tokenID].mixerData[_mixerID].totalDeposits.sub(amount); // Take away from deposits
}
tokenList[_tokenID].mixerData[_mixerID].depositSinceWithdraw = 0; // Reset withdraws
}
// Token IDs
// 0 - DAI
// 1 - USDC
// 2 - USDT
// 3 - yUSD
// 4 - LINK
// 5 - wBTC
// 6 - renBTC
// 7 - crv renwBTC
function withdrawDAI(bytes calldata _proof, uint256 amount, bytes32 _root,
bytes32 _nullifierHash, address payable _recipient,
address payable _relayer, uint256 _fee, uint256 _refund) external payable {
// The user can send ETH to the recipient
uint256 _tokenID = 0;
require(amount == tokenList[_tokenID].mixerData[0].denomination || amount == tokenList[_tokenID].mixerData[1].denomination, "Can only withdraw either 100 or 1000 DAI");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 0); // DAI 100 withdraw
}else{
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 1); // DAI 1000 withdraw
}
}
function withdrawUSDC(bytes calldata _proof, uint256 amount, bytes32 _root,
bytes32 _nullifierHash, address payable _recipient,
address payable _relayer, uint256 _fee, uint256 _refund) external payable {
// The user can send ETH to the recipient
uint256 _tokenID = 1;
require(amount == tokenList[_tokenID].mixerData[0].denomination || amount == tokenList[_tokenID].mixerData[1].denomination, "Can only withdraw either 100 or 1000 USDC");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 0); // USDC 100 withdraw
}else{
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 1); // USDC 1000 withdraw
}
}
function withdrawUSDT(bytes calldata _proof, uint256 amount, bytes32 _root,
bytes32 _nullifierHash, address payable _recipient,
address payable _relayer, uint256 _fee, uint256 _refund) external payable {
// The user can send ETH to the recipient
uint256 _tokenID = 2;
require(amount == tokenList[_tokenID].mixerData[0].denomination || amount == tokenList[_tokenID].mixerData[1].denomination, "Can only withdraw either 100 or 1000 USDT");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 0); // USDT 100 withdraw
}else{
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 1); // USDT 1000 withdraw
}
}
function withdrawYUSD(bytes calldata _proof, uint256 amount, bytes32 _root,
bytes32 _nullifierHash, address payable _recipient,
address payable _relayer, uint256 _fee, uint256 _refund) external payable {
// The user can send ETH to the recipient
uint256 _tokenID = 3;
require(amount == tokenList[_tokenID].mixerData[0].denomination || amount == tokenList[_tokenID].mixerData[1].denomination, "Can only withdraw either 100 or 1000 yUSD");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 0); // yUSD 100 withdraw
}else{
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 1); // yUSD 1000 withdraw
}
}
function withdrawLINK(bytes calldata _proof, uint256 amount, bytes32 _root,
bytes32 _nullifierHash, address payable _recipient,
address payable _relayer, uint256 _fee, uint256 _refund) external payable {
// The user can send ETH to the recipient
uint256 _tokenID = 4;
require(amount == tokenList[_tokenID].mixerData[0].denomination || amount == tokenList[_tokenID].mixerData[1].denomination, "Can only withdraw either 10 or 100 LINK");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 0); // LINK 10 withdraw
}else{
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 1); // LINK 100 withdraw
}
}
function withdrawWBTC(bytes calldata _proof, uint256 amount, bytes32 _root,
bytes32 _nullifierHash, address payable _recipient,
address payable _relayer, uint256 _fee, uint256 _refund) external payable {
// The user can send ETH to the recipient
uint256 _tokenID = 5;
require(amount == tokenList[_tokenID].mixerData[0].denomination
|| amount == tokenList[_tokenID].mixerData[1].denomination
|| amount == tokenList[_tokenID].mixerData[2].denomination, "Can only withdraw either 0.01, 0.1 or 1 wBTC");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 0); // wBTC 0.01 withdraw
}else if(amount == tokenList[_tokenID].mixerData[1].denomination){
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 1); // wBTC 0.1 withdraw
}else{
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 2); // wBTC 1 withdraw
}
}
function withdrawRenBTC(bytes calldata _proof, uint256 amount, bytes32 _root,
bytes32 _nullifierHash, address payable _recipient,
address payable _relayer, uint256 _fee, uint256 _refund) external payable {
// The user can send ETH to the recipient
uint256 _tokenID = 6;
require(amount == tokenList[_tokenID].mixerData[0].denomination
|| amount == tokenList[_tokenID].mixerData[1].denomination
|| amount == tokenList[_tokenID].mixerData[2].denomination, "Can only withdraw either 0.01, 0.1 or 1 renBTC");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 0); // renBTC 0.01 withdraw
}else if(amount == tokenList[_tokenID].mixerData[1].denomination){
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 1); // renBTC 0.1 withdraw
}else{
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 2); // renBTC 1 withdraw
}
}
function withdrawCrvRenWBTC(bytes calldata _proof, uint256 amount, bytes32 _root,
bytes32 _nullifierHash, address payable _recipient,
address payable _relayer, uint256 _fee, uint256 _refund) external payable {
// The user can send ETH to the recipient
uint256 _tokenID = 7;
require(amount == tokenList[_tokenID].mixerData[0].denomination
|| amount == tokenList[_tokenID].mixerData[1].denomination
|| amount == tokenList[_tokenID].mixerData[2].denomination, "Can only withdraw either 0.01, 0.1 or 1 CRV renwBTC");
if(amount == tokenList[_tokenID].mixerData[0].denomination){
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 0); // Crv renwBTC 0.01 withdraw
}else if(amount == tokenList[_tokenID].mixerData[1].denomination){
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 1); // Crv renwBTC 0.1 withdraw
}else{
_withdraw(_proof, amount, _root, _nullifierHash, _recipient, _relayer, _fee, _refund, _tokenID, 2); // Crv renwBTC 1 withdraw
}
}
// Governance functions
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant _timelockDuration = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
uint256 private _timelock_data_1;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
require(now >= _timelockStart + _timelockDuration, "Timelock time not met");
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeTreasury(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
}
function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) {
treasuryAddress = _timelock_address;
}
// --------------------
// Change the non stablecoin fee
// --------------------
function startChangeNonStableFee(uint256 _fee) external onlyGovernance {
require(_fee <= 5000,"Fee can never be greater than 5%");
_timelockStart = now;
_timelockType = 3;
_timelock_data_1 = _fee;
}
function finishChangeNonStableFee() external onlyGovernance timelockConditionsMet(3) {
nonStableFee = _timelock_data_1;
}
// --------------------
} | The user can send ETH to the recipient | address payable _relayer, uint256 _fee, uint256 _refund) external payable {
uint256 _tokenID = 6;
require(amount == tokenList[_tokenID].mixerData[0].denomination
|| amount == tokenList[_tokenID].mixerData[1].denomination
|| amount == tokenList[_tokenID].mixerData[2].denomination, "Can only withdraw either 0.01, 0.1 or 1 renBTC");
function withdrawRenBTC(bytes calldata _proof, uint256 amount, bytes32 _root,
bytes32 _nullifierHash, address payable _recipient,
if(amount == tokenList[_tokenID].mixerData[0].denomination){
}
}else if(amount == tokenList[_tokenID].mixerData[1].denomination){
}else{
}
| 6,301,288 | [
1,
1986,
729,
848,
1366,
512,
2455,
358,
326,
8027,
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,
13491,
1758,
8843,
429,
389,
2878,
1773,
16,
2254,
5034,
389,
21386,
16,
2254,
5034,
389,
1734,
1074,
13,
3903,
8843,
429,
288,
203,
18701,
2254,
5034,
389,
2316,
734,
273,
1666,
31,
203,
18701,
2583,
12,
8949,
422,
1147,
682,
63,
67,
2316,
734,
8009,
14860,
264,
751,
63,
20,
8009,
13002,
362,
1735,
7010,
18701,
747,
3844,
422,
1147,
682,
63,
67,
2316,
734,
8009,
14860,
264,
751,
63,
21,
8009,
13002,
362,
1735,
203,
18701,
747,
3844,
422,
1147,
682,
63,
67,
2316,
734,
8009,
14860,
264,
751,
63,
22,
8009,
13002,
362,
1735,
16,
315,
2568,
1338,
598,
9446,
3344,
374,
18,
1611,
16,
374,
18,
21,
578,
404,
1654,
38,
15988,
8863,
203,
565,
445,
598,
9446,
16290,
38,
15988,
12,
3890,
745,
892,
389,
24207,
16,
2254,
5034,
3844,
16,
1731,
1578,
389,
3085,
16,
7010,
13491,
1731,
1578,
389,
2011,
1251,
2310,
16,
1758,
8843,
429,
389,
20367,
16,
7010,
18701,
309,
12,
8949,
422,
1147,
682,
63,
67,
2316,
734,
8009,
14860,
264,
751,
63,
20,
8009,
13002,
362,
1735,
15329,
203,
18701,
289,
203,
18701,
289,
12107,
309,
12,
8949,
422,
1147,
682,
63,
67,
2316,
734,
8009,
14860,
264,
751,
63,
21,
8009,
13002,
362,
1735,
15329,
203,
18701,
289,
12107,
95,
203,
13491,
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
]
|
/**
*
*
/$$$$$$$$ /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$ /$$$$$$$$
| $$_____//$$__ $$| $$ | $$ /$$__ $$| $$__ $$ | $$ | $$ /$$__ $$| $$__ $$| $$_____/
| $$ | $$ \ $$| $$ | $$| $$ \ $$| $$ \ $$ | $$ | $$| $$ \__/| $$ \ $$| $$
| $$$$$ | $$$$$$$$| $$ / $$/| $$ | $$| $$$$$$$/ | $$ | $$| $$$$$$ | $$ | $$| $$$$$
| $$__/ | $$__ $$ \ $$ $$/ | $$ | $$| $$__ $$ | $$ | $$ \____ $$| $$ | $$| $$__/
| $$ | $$ | $$ \ $$$/ | $$ | $$| $$ \ $$ | $$ | $$ /$$ \ $$| $$ | $$| $$
| $$ | $$ | $$ \ $/ | $$$$$$/| $$ | $$ | $$$$$$/| $$$$$$/| $$$$$$$/| $$
|__/ |__/ |__/ \_/ \______/ |__/ |__/ \______/ \______/ |_______/ |__/
εɖɖίε રεĢĢίε ĵΘε
*
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import {ERC20} from "./ERC20.sol";
import {FavorCurrency} from "./FavorCurrency.sol";
import {ClaimableOwnable} from "./ClaimableOwnable.sol";
library SafeMath {
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
}
/**
* @title FavorUSD
* @dev This is the top-level ERC20 contract, but most of the interesting functionality is
* inherited - see the documentation on the corresponding contracts.
*/
contract FavorUSD is FavorCurrency {
using SafeMath for uint256;
uint8 constant DECIMALS = 18;
uint8 constant ROUNDING = 2;
function initialize() external {
require(!initialized);
owner = msg.sender;
initialized = true;
}
function decimals() public override pure returns (uint8) {
return DECIMALS;
}
function rounding() public pure returns (uint8) {
return ROUNDING;
}
function name() public override pure returns (string memory) {
return "FavorUSD";
}
function symbol() public override pure returns (string memory) {
return "USDF";
}
function donate() public payable {}
function burnFrom(address _to, uint256 _amount) external onlyOwner() returns (bool) {
transferFrom(_to, msg.sender, _amount);
_burn(msg.sender, _amount);
return true;
}
} | * @title FavorUSD @dev This is the top-level ERC20 contract, but most of the interesting functionality is inherited - see the documentation on the corresponding contracts./ | contract FavorUSD is FavorCurrency {
using SafeMath for uint256;
uint8 constant DECIMALS = 18;
uint8 constant ROUNDING = 2;
function initialize() external {
require(!initialized);
owner = msg.sender;
initialized = true;
}
function decimals() public override pure returns (uint8) {
return DECIMALS;
}
function rounding() public pure returns (uint8) {
return ROUNDING;
}
function name() public override pure returns (string memory) {
return "FavorUSD";
}
function symbol() public override pure returns (string memory) {
return "USDF";
}
function donate() public payable {}
function burnFrom(address _to, uint256 _amount) external onlyOwner() returns (bool) {
transferFrom(_to, msg.sender, _amount);
_burn(msg.sender, _amount);
return true;
}
} | 10,228,901 | [
1,
31745,
3378,
40,
225,
1220,
353,
326,
1760,
17,
2815,
4232,
39,
3462,
6835,
16,
1496,
4486,
434,
326,
26122,
14176,
353,
12078,
300,
2621,
326,
7323,
603,
326,
4656,
20092,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
16351,
478,
9444,
3378,
40,
353,
478,
9444,
7623,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
377,
203,
565,
2254,
28,
5381,
25429,
55,
273,
6549,
31,
203,
565,
2254,
28,
5381,
27048,
1360,
273,
576,
31,
203,
203,
565,
445,
4046,
1435,
3903,
288,
203,
3639,
2583,
12,
5,
13227,
1769,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
3639,
6454,
273,
638,
31,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
3849,
16618,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
25429,
55,
31,
203,
565,
289,
203,
203,
565,
445,
13885,
1435,
1071,
16618,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
27048,
1360,
31,
203,
565,
289,
203,
203,
565,
445,
508,
1435,
1071,
3849,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
315,
31745,
3378,
40,
14432,
203,
565,
289,
203,
203,
565,
445,
3273,
1435,
1071,
3849,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
315,
3378,
4577,
14432,
203,
565,
289,
203,
377,
203,
203,
203,
7010,
565,
445,
2727,
340,
1435,
1071,
8843,
429,
2618,
203,
565,
445,
18305,
1265,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
3903,
1338,
5541,
1435,
1135,
261,
6430,
13,
288,
203,
3639,
7412,
1265,
24899,
869,
16,
1234,
18,
15330,
16,
389,
8949,
1769,
203,
3639,
389,
70,
321,
12,
3576,
18,
15330,
16,
389,
8949,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
97,
2,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.13;
/**
*
* Concept:
*
* Phase 1
* =======
*
* Create a 2 dimensional board of 100 x 100 squares
* Allow a person to purchase a single square and set its colour
*
* Phase 2
* =======
* Allow a person to purchase a set of squares and set its colour
*
**/
contract BasicBoard {
struct Coordinate {
uint8 x;
uint8 y;
}
struct Owner {
address owner; // owner of pixel
uint price; // price of pixel
string colour; // pixel colour
uint32 purchasedDateTime; // approx time it was purchased
Coordinate coordinate; // the purchased Coordinate
}
// Events
event Purchased(uint fromX, uint toX, uint fromY, uint toY, string colour, address owner);
/**
* Maximum board width
*/
uint public maxWidth = 1000;
/**
* Maximum board height
*/
uint public maxHeight = 1000;
/**
* Block size - size of a block (10x10 pixels)
*/
uint public blockSize = 10;
/**
* The basic board - a X -> Y -> Owner
*/
mapping (uint => mapping (uint => Owner)) private board;
/**
* Who created the board
*/
address private boardCreator;
/**
* emergency kill switch, disables all future sales
*/
bool public stopped = false;
/**
* Board constructor
*/
function BasicBoard() public {
boardCreator = msg.sender;
}
// Accessors
function purchaseSpace (uint8 fromX, uint8 toX, uint8 fromY, uint8 toY, string colour)
stopInEmergency
validateWithinBoardBoundary(fromX, toX, fromY, toY)
public payable returns(bool)
{
// TODO validate price?
// TODO how allow owner to sell block?
// iterate the pixel space
for (uint8 ix = fromX; ix <= toX; ix++) {
for (uint8 iy = fromY; iy <= toY; iy++) {
buyPixel(ix, iy, colour);
}
}
// fire purchased event
Purchased(fromX, toX, fromY, toY, colour, msg.sender);
return true;
}
function buyPixel (uint8 x, uint8 y, string colour)
private
isForSale(x, y)
returns (uint)
{
// Set block to colour at location
board[x][y] = Owner({
owner: msg.sender,
price: msg.value, // TODO is this price per pixel of total price?
colour: colour,
purchasedDateTime: uint32(block.timestamp),
coordinate: Coordinate({x:x, y:y})
});
}
/**
* Return coordinate details
*/
function getCoordinateDetails(uint8 x, uint8 y)
public constant
returns (address owner, uint price, string colour, uint32 purchasedDateTime) {
Owner storage o = board[x][y];
return (o.owner, o.price, o.colour, o.purchasedDateTime);
}
// TODO add function to get all pixels the caller owners
modifier isForSale (uint8 x, uint8 y) {
// Look up the existing area block
Owner storage existingOwner = board[x][y];
// validate area is available OR is owned by caller
require(existingOwner.owner == 0 || existingOwner.owner == msg.sender);
_;
}
/**
* Validator - the kill switch
*/
function toggleContractActive() isBoardAdmin public {
stopped = !stopped;
}
/**
* Validator - fails when not the board admin i.e. the creator
*/
modifier isBoardAdmin {
assert(msg.sender == boardCreator);
_;
}
/**
* Validator - fails when area exceeds board boundary
*/
modifier validateWithinBoardBoundary(uint fromX, uint toX, uint fromY, uint toY) {
assert(fromX >= 0 && toX <= maxWidth - 1);
assert(fromY >= 0 && toY <= maxHeight - 1);
_;
}
// kill switch validators
modifier stopInEmergency {
require(!stopped);
_;
}
modifier onlyInEmergency {
if (stopped)
_;
}
}
| fire purchased event | Purchased(fromX, toX, fromY, toY, colour, msg.sender);
| 6,442,572 | [
1,
12179,
5405,
343,
8905,
871,
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,
202,
202,
10262,
343,
8905,
12,
2080,
60,
16,
358,
60,
16,
628,
61,
16,
358,
61,
16,
15046,
16,
1234,
18,
15330,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "../Plus.sol";
import "./MockToken.sol";
/**
* @dev Mock plus implementation.
*/
contract MockPlus is Plus {
uint256 public underlyingAmount;
function initialize(string memory _name, string memory _symbol) public {
__PlusToken__init(_name, _symbol);
}
/**
* @dev Returns the total value of the plus token in terms of the peg value.
* All underlying token amounts have been scaled to 18 decimals.
* For single plus, it's equal to its total supply.
* For composite plus, it's equal to the total amount of single plus tokens in its basket.
*/
function _totalUnderlyingInWad() internal view virtual override returns (uint256) {
return underlyingAmount * WAD;
}
function increment(uint256 amount) public {
underlyingAmount = underlyingAmount + amount;
}
function mintShares(address user, uint256 amount) public {
totalShares += amount;
userShare[user] += amount;
underlyingAmount += amount * index / WAD;
}
/**
* @dev Checks whether a token can be salvaged via salvageToken().
* @param _token Token to check salvageability.
*/
function _salvageable(address _token) internal view override returns (bool) {
underlyingAmount;
return _token != address(0x0);
}
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
function burn(address account, uint256 amount) public {
_burn(account, amount);
}
} | * @dev Mock plus implementation./ | contract MockPlus is Plus {
uint256 public underlyingAmount;
pragma solidity 0.8.0;
function initialize(string memory _name, string memory _symbol) public {
__PlusToken__init(_name, _symbol);
}
function _totalUnderlyingInWad() internal view virtual override returns (uint256) {
return underlyingAmount * WAD;
}
function increment(uint256 amount) public {
underlyingAmount = underlyingAmount + amount;
}
function mintShares(address user, uint256 amount) public {
totalShares += amount;
userShare[user] += amount;
underlyingAmount += amount * index / WAD;
}
function _salvageable(address _token) internal view override returns (bool) {
underlyingAmount;
return _token != address(0x0);
}
function mint(address account, uint256 amount) public {
_mint(account, amount);
}
function burn(address account, uint256 amount) public {
_burn(account, amount);
}
} | 7,292,858 | [
1,
9865,
8737,
4471,
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,
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,
16351,
7867,
13207,
353,
3008,
407,
288,
203,
565,
2254,
5034,
1071,
6808,
6275,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
20,
31,
203,
565,
445,
4046,
12,
1080,
3778,
389,
529,
16,
533,
3778,
389,
7175,
13,
1071,
288,
203,
3639,
1001,
13207,
1345,
972,
2738,
24899,
529,
16,
389,
7175,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
4963,
14655,
6291,
382,
59,
361,
1435,
2713,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
6808,
6275,
380,
678,
1880,
31,
203,
565,
289,
203,
203,
565,
445,
5504,
12,
11890,
5034,
3844,
13,
1071,
288,
203,
3639,
6808,
6275,
273,
6808,
6275,
397,
3844,
31,
203,
565,
289,
203,
203,
565,
445,
312,
474,
24051,
12,
2867,
729,
16,
2254,
5034,
3844,
13,
1071,
288,
203,
3639,
2078,
24051,
1011,
3844,
31,
203,
3639,
729,
9535,
63,
1355,
65,
1011,
3844,
31,
203,
3639,
6808,
6275,
1011,
3844,
380,
770,
342,
678,
1880,
31,
7010,
565,
289,
203,
203,
565,
445,
389,
21982,
90,
410,
429,
12,
2867,
389,
2316,
13,
2713,
1476,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
6808,
6275,
31,
203,
3639,
327,
389,
2316,
480,
1758,
12,
20,
92,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
312,
474,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
1071,
288,
203,
3639,
389,
81,
474,
12,
4631,
16,
3844,
1769,
203,
565,
289,
203,
203,
565,
445,
18305,
12,
2867,
2236,
16,
2254,
5034,
3844,
13,
1071,
288,
2
]
|
./full_match/4/0x99d2cDe8150CB781DDe2495b282e6dF0Ae63aE33/sources/teststorage/view.sol | 现在我们可以调用在那个合约中声明的 `getNum`函数: ...在这儿使用 `num`变量做些什么 | function someFunction() public {
aa = numberContract.getNum();
}
| 12,530,543 | [
1,
168,
241,
113,
166,
255,
106,
167,
235,
244,
165,
124,
110,
166,
242,
112,
165,
124,
103,
169,
113,
230,
168,
247,
106,
166,
255,
106,
170,
229,
101,
165,
121,
108,
166,
243,
235,
168,
123,
104,
165,
121,
260,
166,
101,
113,
167,
251,
241,
168,
253,
231,
1375,
588,
2578,
68,
166,
234,
126,
167,
248,
113,
30,
1372,
166,
255,
106,
169,
128,
252,
166,
231,
128,
165,
126,
128,
168,
247,
106,
1375,
2107,
68,
166,
242,
251,
170,
234,
242,
166,
228,
253,
165,
123,
254,
165,
124,
227,
165,
122,
235,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
225,
445,
2690,
2083,
1435,
1071,
288,
203,
565,
12391,
273,
1300,
8924,
18,
588,
2578,
5621,
203,
377,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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 2020-04-02
*/
// Sources flattened with buidler v1.2.0 https://buidler.dev
// File @pie-dao/proxy/contracts/[email protected]
pragma solidity ^0.6.2;
contract PProxyStorage {
function readString(bytes32 _key) public view returns(string memory) {
return bytes32ToString(storageRead(_key));
}
function setString(bytes32 _key, string memory _value) internal {
storageSet(_key, stringToBytes32(_value));
}
function readBool(bytes32 _key) public view returns(bool) {
return storageRead(_key) == bytes32(uint256(1));
}
function setBool(bytes32 _key, bool _value) internal {
if(_value) {
storageSet(_key, bytes32(uint256(1)));
} else {
storageSet(_key, bytes32(uint256(0)));
}
}
function readAddress(bytes32 _key) public view returns(address) {
return bytes32ToAddress(storageRead(_key));
}
function setAddress(bytes32 _key, address _value) internal {
storageSet(_key, addressToBytes32(_value));
}
function storageRead(bytes32 _key) public view returns(bytes32) {
bytes32 value;
//solium-disable-next-line security/no-inline-assembly
assembly {
value := sload(_key)
}
return value;
}
function storageSet(bytes32 _key, bytes32 _value) internal {
// targetAddress = _address; // No!
bytes32 implAddressStorageKey = _key;
//solium-disable-next-line security/no-inline-assembly
assembly {
sstore(implAddressStorageKey, _value)
}
}
function bytes32ToAddress(bytes32 _value) public pure returns(address) {
return address(uint160(uint256(_value)));
}
function addressToBytes32(address _value) public pure returns(bytes32) {
return bytes32(uint256(_value));
}
function stringToBytes32(string memory _value) public pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(_value);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(_value, 32))
}
}
function bytes32ToString(bytes32 _value) public pure returns (string memory) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint256 j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(_value) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint256 j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
}
// File @pie-dao/proxy/contracts/[email protected]
pragma solidity ^0.6.2;
contract PProxy is PProxyStorage {
bytes32 constant IMPLEMENTATION_SLOT = keccak256(abi.encodePacked("IMPLEMENTATION_SLOT"));
bytes32 constant OWNER_SLOT = keccak256(abi.encodePacked("OWNER_SLOT"));
modifier onlyProxyOwner() {
require(msg.sender == readAddress(OWNER_SLOT), "PProxy.onlyProxyOwner: msg sender not owner");
_;
}
constructor () public {
setAddress(OWNER_SLOT, msg.sender);
}
function getProxyOwner() public view returns (address) {
return readAddress(OWNER_SLOT);
}
function setProxyOwner(address _newOwner) onlyProxyOwner public {
setAddress(OWNER_SLOT, _newOwner);
}
function getImplementation() public view returns (address) {
return readAddress(IMPLEMENTATION_SLOT);
}
function setImplementation(address _newImplementation) onlyProxyOwner public {
setAddress(IMPLEMENTATION_SLOT, _newImplementation);
}
fallback () external payable {
return internalFallback();
}
function internalFallback() internal virtual {
address contractAddr = readAddress(IMPLEMENTATION_SLOT);
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), contractAddr, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
// File @pie-dao/proxy/contracts/[email protected]
pragma solidity ^0.6.2;
contract PProxyPausable is PProxy {
bytes32 constant PAUSED_SLOT = keccak256(abi.encodePacked("PAUSED_SLOT"));
bytes32 constant PAUZER_SLOT = keccak256(abi.encodePacked("PAUZER_SLOT"));
constructor() PProxy() public {
setAddress(PAUZER_SLOT, msg.sender);
}
modifier onlyPauzer() {
require(msg.sender == readAddress(PAUZER_SLOT), "PProxyPausable.onlyPauzer: msg sender not pauzer");
_;
}
modifier notPaused() {
require(!readBool(PAUSED_SLOT), "PProxyPausable.notPaused: contract is paused");
_;
}
function getPauzer() public view returns (address) {
return readAddress(PAUZER_SLOT);
}
function setPauzer(address _newPauzer) public onlyProxyOwner{
setAddress(PAUZER_SLOT, _newPauzer);
}
function renouncePauzer() public onlyPauzer {
setAddress(PAUZER_SLOT, address(0));
}
function getPaused() public view returns (bool) {
return readBool(PAUSED_SLOT);
}
function setPaused(bool _value) public onlyPauzer {
setBool(PAUSED_SLOT, _value);
}
function internalFallback() internal virtual override notPaused {
super.internalFallback();
}
}
// File contracts/interfaces/IBFactory.sol
pragma solidity ^0.6.4;
interface IBFactory {
function newBPool() external returns (address);
}
// File contracts/interfaces/IBPool.sol
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is disstributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity 0.6.4;
interface IBPool {
function isBound(address token) external view returns(bool);
function getBalance(address token) external view returns (uint);
function rebind(address token, uint balance, uint denorm) external;
function setSwapFee(uint swapFee) external;
function setPublicSwap(bool _public) external;
function bind(address token, uint balance, uint denorm) external;
function unbind(address token) external;
function getDenormalizedWeight(address token) external view returns (uint);
function getTotalDenormalizedWeight() external view returns (uint);
function getCurrentTokens() external view returns(address[] memory);
function setController(address manager) external;
function isPublicSwap() external view returns(bool);
function getSwapFee() external view returns (uint256);
function gulp(address token) external;
function calcPoolOutGivenSingleIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint tokenAmountIn,
uint swapFee
)
external pure
returns (uint poolAmountOut);
function calcSingleInGivenPoolOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint poolAmountOut,
uint swapFee
)
external pure
returns (uint tokenAmountIn);
function calcSingleOutGivenPoolIn(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint poolAmountIn,
uint swapFee
)
external pure
returns (uint tokenAmountOut);
function calcPoolInGivenSingleOut(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint tokenAmountOut,
uint swapFee
)
external pure
returns (uint poolAmountIn);
}
// File contracts/interfaces/IERC20.sol
pragma solidity ^0.6.4;
interface IERC20 {
event Approval(address indexed _src, address indexed _dst, uint _amount);
event Transfer(address indexed _src, address indexed _dst, uint _amount);
function totalSupply() external view returns (uint);
function balanceOf(address _whom) external view returns (uint);
function allowance(address _src, address _dst) external view returns (uint);
function approve(address _dst, uint _amount) external returns (bool);
function transfer(address _dst, uint _amount) external returns (bool);
function transferFrom(
address _src, address _dst, uint _amount
) external returns (bool);
}
// File contracts/Ownable.sol
pragma solidity ^0.6.4;
// TODO move this generic contract to a seperate repo with all generic smart contracts
contract Ownable {
bytes32 constant public oSlot = keccak256("Ownable.storage.location");
event OwnerChanged(address indexed previousOwner, address indexed newOwner);
// Ownable struct
struct os {
address owner;
}
modifier onlyOwner(){
require(msg.sender == los().owner, "Ownable.onlyOwner: msg.sender not owner");
_;
}
/**
@notice Transfer ownership to a new address
@param _newOwner Address of the new owner
*/
function transferOwnership(address _newOwner) onlyOwner external {
_setOwner(_newOwner);
}
/**
@notice Internal method to set the owner
@param _newOwner Address of the new owner
*/
function _setOwner(address _newOwner) internal {
emit OwnerChanged(los().owner, _newOwner);
los().owner = _newOwner;
}
/**
@notice Load ownable storage
@return s Storage pointer to the Ownable storage struct
*/
function los() internal pure returns (os storage s) {
bytes32 loc = oSlot;
assembly {
s_slot := loc
}
}
}
// File contracts/interfaces/IPSmartPool.sol
pragma solidity ^0.6.4;
interface IPSmartPool is IERC20 {
function joinPool(uint256 _amount) external;
function exitPool(uint256 _amount) external;
function getController() external view returns(address);
function getTokens() external view returns(address[] memory);
function calcTokensForAmount(uint256 _amount) external view returns(address[] memory tokens, uint256[] memory amounts);
}
// File contracts/PCTokenStorage.sol
pragma solidity ^0.6.4;
contract PCTokenStorage {
bytes32 constant public ptSlot = keccak256("PCToken.storage.location");
struct pts {
string name;
string symbol;
uint256 totalSupply;
mapping(address => uint256) balance;
mapping(address => mapping(address=>uint256)) allowance;
}
/**
@notice Load pool token storage
@return s Storage pointer to the pool token struct
*/
function lpts() internal pure returns (pts storage s) {
bytes32 loc = ptSlot;
assembly {
s_slot := loc
}
}
}
// File contracts/PCToken.sol
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.6.4;
// Highly opinionated token implementation
// Based on the balancer Implementation
contract PCToken is IERC20, PCTokenStorage {
event Approval(address indexed _src, address indexed _dst, uint _amount);
event Transfer(address indexed _src, address indexed _dst, uint _amount);
uint8 public constant decimals = 18;
uint public constant BONE = 10**18;
uint public constant MAX_BOUND_TOKENS = 8;
uint public constant MIN_WEIGHT = BONE;
uint public constant MAX_WEIGHT = BONE * 50;
uint public constant MAX_TOTAL_WEIGHT = BONE * 50;
uint public constant MIN_BALANCE = BONE / 10**6;
uint public constant MAX_BALANCE = BONE * 10**12;
uint public constant MIN_POOL_SUPPLY = BONE;
function badd(uint a, uint b)
internal pure
returns (uint)
{
uint c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
function bsub(uint a, uint b)
internal pure
returns (uint)
{
(uint c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
function bsubSign(uint a, uint b)
internal pure
returns (uint, bool)
{
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bmul(uint a, uint b)
internal pure
returns (uint)
{
uint c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint c2 = c1 / BONE;
return c2;
}
function bdiv(uint a, uint b)
internal pure
returns (uint)
{
require(b != 0, "ERR_DIV_ZERO");
uint c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint c2 = c1 / b;
return c2;
}
function _mint(uint _amount) internal {
pts storage s = lpts();
s.balance[address(this)] = badd(s.balance[address(this)], _amount);
s.totalSupply = badd(s.totalSupply, _amount);
emit Transfer(address(0), address(this), _amount);
}
function _burn(uint _amount) internal {
pts storage s = lpts();
require(s.balance[address(this)] >= _amount, "ERR_INSUFFICIENT_BAL");
s.balance[address(this)] = bsub(s.balance[address(this)], _amount);
s.totalSupply = bsub(s.totalSupply, _amount);
emit Transfer(address(this), address(0), _amount);
}
function _move(address _src, address _dst, uint _amount) internal {
pts storage s = lpts();
require(s.balance[_src] >= _amount, "ERR_INSUFFICIENT_BAL");
s.balance[_src] = bsub(s.balance[_src], _amount);
s.balance[_dst] = badd(s.balance[_dst], _amount);
emit Transfer(_src, _dst, _amount);
}
function _push(address _to, uint _amount) internal {
_move(address(this), _to, _amount);
}
function _pull(address _from, uint _amount) internal {
_move(_from, address(this), _amount);
}
function allowance(address _src, address _dst) external view override returns (uint) {
return lpts().allowance[_src][_dst];
}
function balanceOf(address _whom) external view override returns (uint) {
return lpts().balance[_whom];
}
function totalSupply() public view override returns (uint) {
return lpts().totalSupply;
}
function name() external view returns (string memory) {
return lpts().name;
}
function symbol() external view returns (string memory) {
return lpts().symbol;
}
function approve(address _dst, uint _amount) external override returns (bool) {
lpts().allowance[msg.sender][_dst] = _amount;
emit Approval(msg.sender, _dst, _amount);
return true;
}
function increaseApproval(address _dst, uint _amount) external returns (bool) {
pts storage s = lpts();
s.allowance[msg.sender][_dst] = badd(s.allowance[msg.sender][_dst], _amount);
emit Approval(msg.sender, _dst, s.allowance[msg.sender][_dst]);
return true;
}
function decreaseApproval(address _dst, uint _amount) external returns (bool) {
pts storage s = lpts();
uint oldValue = s.allowance[msg.sender][_dst];
if (_amount > oldValue) {
s.allowance[msg.sender][_dst] = 0;
} else {
s.allowance[msg.sender][_dst] = bsub(oldValue, _amount);
}
emit Approval(msg.sender, _dst, s.allowance[msg.sender][_dst]);
return true;
}
function transfer(address _dst, uint _amount) external override returns (bool) {
_move(msg.sender, _dst, _amount);
return true;
}
function transferFrom(address _src, address _dst, uint _amount) external override returns (bool) {
pts storage s = lpts();
require(msg.sender == _src || _amount <= s.allowance[_src][msg.sender], "ERR_PCTOKEN_BAD_CALLER");
_move(_src, _dst, _amount);
if (msg.sender != _src && s.allowance[_src][msg.sender] != uint256(-1)) {
s.allowance[_src][msg.sender] = bsub(s.allowance[_src][msg.sender], _amount);
emit Approval(msg.sender, _dst, s.allowance[_src][msg.sender]);
}
return true;
}
}
// File contracts/ReentryProtection.sol
pragma solidity ^0.6.4;
// TODO move this generic contract to a seperate repo with all generic smart contracts
contract ReentryProtection {
bytes32 constant public rpSlot = keccak256("ReentryProtection.storage.location");
// reentry protection storage
struct rps {
uint256 lockCounter;
}
modifier noReentry {
// Use counter to only write to storage once
lrps().lockCounter ++;
uint256 lockValue = lrps().lockCounter;
_;
require(lockValue == lrps().lockCounter, "ReentryProtection.noReentry: reentry detected");
}
/**
@notice Load reentry protection storage
@return s Pointer to the reentry protection storage struct
*/
function lrps() internal pure returns (rps storage s) {
bytes32 loc = rpSlot;
assembly {
s_slot := loc
}
}
}
// File contracts/smart-pools/PBasicSmartPool.sol
pragma solidity ^0.6.4;
contract PBasicSmartPool is IPSmartPool, PCToken, ReentryProtection {
// P Basic Smart Struct
bytes32 constant public pbsSlot = keccak256("PBasicSmartPool.storage.location");
struct pbs {
IBPool bPool;
address controller;
address publicSwapSetter;
address tokenBinder;
}
modifier ready() {
require(address(lpbs().bPool) != address(0), "PBasicSmartPool.ready: not ready");
_;
}
event LOG_JOIN(
address indexed caller,
address indexed tokenIn,
uint256 tokenAmountIn
);
event LOG_EXIT(
address indexed caller,
address indexed tokenOut,
uint256 tokenAmountOut
);
event TokensApproved();
event ControllerChanged(address indexed previousController, address indexed newController);
event PublicSwapSetterChanged(address indexed previousSetter, address indexed newSetter);
event TokenBinderChanged(address indexed previousTokenBinder, address indexed newTokenBinder);
event PublicSwapSet(address indexed setter, bool indexed value);
event SwapFeeSet(address indexed setter, uint256 newFee);
event PoolJoined(address indexed from, uint256 amount);
event PoolExited(address indexed from, uint256 amount);
modifier onlyController() {
require(msg.sender == lpbs().controller, "PBasicSmartPool.onlyController: not controller");
_;
}
modifier onlyPublicSwapSetter() {
require(msg.sender == lpbs().publicSwapSetter, "PBasicSmartPool.onlyPublicSwapSetter: not public swap setter");
_;
}
modifier onlyTokenBinder() {
require(msg.sender == lpbs().tokenBinder, "PBasicSmartPool.onlyTokenBinder: not token binder");
_;
}
/**
@notice Initialises the contract
@param _bPool Address of the underlying balancer pool
@param _name Name for the smart pool token
@param _symbol Symbol for the smart pool token
@param _initialSupply Initial token supply to mint
*/
function init(address _bPool, string calldata _name, string calldata _symbol, uint256 _initialSupply) external {
pbs storage s = lpbs();
require(address(s.bPool) == address(0), "PBasicSmartPool.init: already initialised");
s.bPool = IBPool(_bPool);
s.controller = msg.sender;
s.publicSwapSetter = msg.sender;
s.tokenBinder = msg.sender;
lpts().name = _name;
lpts().symbol = _symbol;
_mintPoolShare(_initialSupply);
_pushPoolShare(msg.sender, _initialSupply);
}
/**
@notice Sets approval to all tokens to the underlying balancer pool
@dev It uses this function to save on gas in joinPool
*/
function approveTokens() public {
IBPool bPool = lpbs().bPool;
address[] memory tokens = bPool.getCurrentTokens();
for(uint256 i = 0; i < tokens.length; i ++) {
IERC20(tokens[i]).approve(address(bPool), uint256(-1));
}
emit TokensApproved();
}
/**
@notice Sets the controller address. Can only be set by the current controller
@param _controller Address of the new controller
*/
function setController(address _controller) onlyController noReentry external {
emit ControllerChanged(lpbs().controller, _controller);
lpbs().controller = _controller;
}
/**
@notice Sets public swap setter address. Can only be set by the controller
@param _newPublicSwapSetter Address of the new public swap setter
*/
function setPublicSwapSetter(address _newPublicSwapSetter) onlyController external {
emit PublicSwapSetterChanged(lpbs().publicSwapSetter, _newPublicSwapSetter);
lpbs().publicSwapSetter = _newPublicSwapSetter;
}
/**
@notice Sets the token binder address. Can only be set by the controller
@param _newTokenBinder Address of the new token binder
*/
function setTokenBinder(address _newTokenBinder) onlyController external {
emit TokenBinderChanged(lpbs().tokenBinder, _newTokenBinder);
lpbs().tokenBinder = _newTokenBinder;
}
/**
@notice Enables or disables public swapping on the underlying balancer pool. Can only be set by the controller
@param _public Public or not
*/
function setPublicSwap(bool _public) onlyPublicSwapSetter external {
emit PublicSwapSet(msg.sender, _public);
lpbs().bPool.setPublicSwap(_public);
}
/**
@notice Set the swap fee on the underlying balancer pool. Can only be called by the controller
@param _swapFee The new swap fee
*/
function setSwapFee(uint256 _swapFee) onlyController external {
emit SwapFeeSet(msg.sender, _swapFee);
lpbs().bPool.setSwapFee(_swapFee);
}
/**
@notice Mints pool shares in exchange for underlying assets
@param _amount Amount of pool shares to mint
*/
function joinPool(uint256 _amount) external override virtual ready {
_joinPool(_amount);
}
/**
@notice Internal join pool function. See joinPool for more info
@param _amount Amount of pool shares to mint
*/
function _joinPool(uint256 _amount) internal virtual ready {
IBPool bPool = lpbs().bPool;
uint poolTotal = totalSupply();
uint ratio = bdiv(_amount, poolTotal);
require(ratio != 0);
address[] memory tokens = bPool.getCurrentTokens();
for (uint i = 0; i < tokens.length; i++) {
address t = tokens[i];
uint bal = bPool.getBalance(t);
uint tokenAmountIn = bmul(ratio, bal);
emit LOG_JOIN(msg.sender, t, tokenAmountIn);
_pullUnderlying(t, msg.sender, tokenAmountIn, bal);
}
_mintPoolShare(_amount);
_pushPoolShare(msg.sender, _amount);
emit PoolJoined(msg.sender, _amount);
}
/**
@notice Burns pool shares and sends back the underlying assets
@param _amount Amount of pool tokens to burn
*/
function exitPool(uint256 _amount) external override ready noReentry {
IBPool bPool = lpbs().bPool;
uint poolTotal = totalSupply();
uint ratio = bdiv(_amount, poolTotal);
require(ratio != 0);
_pullPoolShare(msg.sender, _amount);
_burnPoolShare(_amount);
address[] memory tokens = bPool.getCurrentTokens();
for (uint i = 0; i < tokens.length; i++) {
address t = tokens[i];
uint bal = bPool.getBalance(t);
uint tAo = bmul(ratio, bal);
emit LOG_EXIT(msg.sender, t, tAo);
_pushUnderlying(t, msg.sender, tAo, bal);
}
emit PoolExited(msg.sender, _amount);
}
/**
@notice Bind a token to the underlying balancer pool. Can only be called by the token binder
@param _token Token to bind
@param _balance Amount to bind
@param _denorm Denormalised weight
*/
function bind(address _token, uint256 _balance, uint256 _denorm) external onlyTokenBinder {
IBPool bPool = lpbs().bPool;
IERC20 token = IERC20(_token);
token.transferFrom(msg.sender, address(this), _balance);
token.approve(address(bPool), uint256(-1));
bPool.bind(_token, _balance, _denorm);
}
/**
@notice Rebind a token to the pool
@param _token Token to bind
@param _balance Amount to bind
@param _denorm Denormalised weight
*/
function rebind(address _token, uint256 _balance, uint256 _denorm) external onlyTokenBinder {
IBPool bPool = lpbs().bPool;
IERC20 token = IERC20(_token);
// gulp old non acounted for token balance in the contract
bPool.gulp(_token);
uint256 oldBalance = token.balanceOf(address(bPool));
// If tokens need to be pulled from msg.sender
if(_balance > oldBalance) {
token.transferFrom(msg.sender, address(this), bsub(_balance, oldBalance));
token.approve(address(bPool), uint256(-1));
}
bPool.rebind(_token, _balance, _denorm);
// If any tokens are in this contract send them to msg.sender
uint256 tokenBalance = token.balanceOf(address(this));
if(tokenBalance > 0) {
token.transfer(msg.sender, tokenBalance);
}
}
/**
@notice Unbind a token
@param _token Token to unbind
*/
function unbind(address _token) external onlyTokenBinder {
IBPool bPool = lpbs().bPool;
IERC20 token = IERC20(_token);
// unbind the token in the bPool
bPool.unbind(_token);
// If any tokens are in this contract send them to msg.sender
uint256 tokenBalance = token.balanceOf(address(this));
if(tokenBalance > 0) {
token.transfer(msg.sender, tokenBalance);
}
}
function getTokens() external view override returns(address[] memory) {
return lpbs().bPool.getCurrentTokens();
}
/**
@notice Gets the underlying assets and amounts to mint specific pool shares.
@param _amount Amount of pool shares to calculate the values for
@return tokens The addresses of the tokens
@return amounts The amounts of tokens needed to mint that amount of pool shares
*/
function calcTokensForAmount(uint256 _amount) external view override returns(address[] memory tokens, uint256[] memory amounts) {
tokens = lpbs().bPool.getCurrentTokens();
amounts = new uint256[](tokens.length);
uint256 ratio = bdiv(_amount, totalSupply());
for(uint256 i = 0; i < tokens.length; i ++) {
address t = tokens[i];
uint256 bal = lpbs().bPool.getBalance(t);
uint256 amount = bmul(ratio, bal);
amounts[i] = amount;
}
}
/**
@notice Get the address of the controller
@return The address of the pool
*/
function getController() external view override returns(address) {
return lpbs().controller;
}
/**
@notice Get the address of the public swap setter
@return The public swap setter address
*/
function getPublicSwapSetter() external view returns(address) {
return lpbs().publicSwapSetter;
}
/**
@notice Get the address of the token binder
@return The token binder address
*/
function getTokenBinder() external view returns(address) {
return lpbs().tokenBinder;
}
/**
@notice Get if public swapping is enabled
@return If public swapping is enabled
*/
function isPublicSwap() external view returns (bool) {
return lpbs().bPool.isPublicSwap();
}
/**
@notice Get the current swap fee
@return The current swap fee
*/
function getSwapFee() external view returns (uint256) {
return lpbs().bPool.getSwapFee();
}
/**
@notice Get the address of the underlying Balancer pool
@return The address of the underlying balancer pool
*/
function getBPool() external view returns(address) {
return address(lpbs().bPool);
}
/**
@notice Pull the underlying token from an address and rebind it to the balancer pool
@param _token Address of the token to pull
@param _from Address to pull the token from
@param _amount Amount of token to pull
@param _tokenBalance Balance of the token already in the balancer pool
*/
function _pullUnderlying(address _token, address _from, uint256 _amount, uint256 _tokenBalance)
internal
{
IBPool bPool = lpbs().bPool;
// Gets current Balance of token i, Bi, and weight of token i, Wi, from BPool.
uint tokenWeight = bPool.getDenormalizedWeight(_token);
bool xfer = IERC20(_token).transferFrom(_from, address(this), _amount);
require(xfer, "ERR_ERC20_FALSE");
bPool.rebind(_token, badd(_tokenBalance, _amount), tokenWeight);
}
/**
@notice Push a underlying token and rebind the token to the balancer pool
@param _token Address of the token to push
@param _to Address to pull the token to
@param _amount Amount of token to push
@param _tokenBalance Balance of the token already in the balancer pool
*/
function _pushUnderlying(address _token, address _to, uint256 _amount, uint256 _tokenBalance)
internal
{
IBPool bPool = lpbs().bPool;
// Gets current Balance of token i, Bi, and weight of token i, Wi, from BPool.
uint tokenWeight = bPool.getDenormalizedWeight(_token);
bPool.rebind(_token, bsub(_tokenBalance, _amount), tokenWeight);
bool xfer = IERC20(_token).transfer(_to, _amount);
require(xfer, "ERR_ERC20_FALSE");
}
/**
@notice Pull pool shares
@param _from Address to pull pool shares from
@param _amount Amount of pool shares to pull
*/
function _pullPoolShare(address _from, uint256 _amount)
internal
{
_pull(_from, _amount);
}
/**
@notice Burn pool shares
@param _amount Amount of pool shares to burn
*/
function _burnPoolShare(uint256 _amount)
internal
{
_burn(_amount);
}
/**
@notice Mint pool shares
@param _amount Amount of pool shares to mint
*/
function _mintPoolShare(uint256 _amount)
internal
{
_mint(_amount);
}
/**
@notice Push pool shares to account
@param _to Address to push the pool shares to
@param _amount Amount of pool shares to push
*/
function _pushPoolShare(address _to, uint256 _amount)
internal
{
_push(_to, _amount);
}
/**
@notice Load PBasicPool storage
@return s Pointer to the storage struct
*/
function lpbs() internal pure returns (pbs storage s) {
bytes32 loc = pbsSlot;
assembly {
s_slot := loc
}
}
}
// File contracts/smart-pools/PCappedSmartPool.sol
pragma solidity ^0.6.4;
contract PCappedSmartPool is PBasicSmartPool {
bytes32 constant public pcsSlot = keccak256("PCappedSmartPool.storage.location");
event CapChanged(address indexed setter, uint256 oldCap, uint256 newCap);
struct pcs {
uint256 cap;
}
modifier withinCap() {
_;
require(totalSupply() < lpcs().cap, "PCappedSmartPool.withinCap: Cap limit reached");
}
/**
@notice Set the maximum cap of the contract
@param _cap New cap in wei
*/
function setCap(uint256 _cap) onlyController external {
emit CapChanged(msg.sender, lpcs().cap, _cap);
lpcs().cap = _cap;
}
/**
@notice Takes underlying assets and mints smart pool tokens. Enforces the cap
@param _amount Amount of pool tokens to mint
*/
function joinPool(uint256 _amount) external override withinCap {
super._joinPool(_amount);
}
/**
@notice Get the current cap
@return The current cap in wei
*/
function getCap() external view returns(uint256) {
return lpcs().cap;
}
/**
@notice Load the PCappedSmartPool storage
@return s Pointer to the storage struct
*/
function lpcs() internal pure returns (pcs storage s) {
bytes32 loc = pcsSlot;
assembly {
s_slot := loc
}
}
}
// File contracts/factory/PProxiedFactory.sol
pragma solidity ^0.6.4;
contract PProxiedFactory is Ownable {
IBFactory public balancerFactory;
address public smartPoolImplementation;
mapping(address => bool) public isPool;
address[] public pools;
event SmartPoolCreated(address indexed poolAddress, string name, string symbol);
function init(address _balancerFactory) public {
require(smartPoolImplementation == address(0), "Already initialised");
_setOwner(msg.sender);
balancerFactory = IBFactory(_balancerFactory);
PCappedSmartPool implementation = new PCappedSmartPool();
// function init(address _bPool, string calldata _name, string calldata _symbol, uint256 _initialSupply) external {
implementation.init(address(0), "IMPL", "IMPL", 1 ether);
smartPoolImplementation = address(implementation);
}
function newProxiedSmartPool(
string memory _name,
string memory _symbol,
uint256 _initialSupply,
address[] memory _tokens,
uint256[] memory _amounts,
uint256[] memory _weights,
uint256 _cap
) public onlyOwner returns(address) {
// Deploy proxy contract
PProxyPausable proxy = new PProxyPausable();
// Setup proxy
proxy.setImplementation(smartPoolImplementation);
proxy.setPauzer(msg.sender);
proxy.setProxyOwner(msg.sender);
// Setup balancer pool
address balancerPoolAddress = balancerFactory.newBPool();
IBPool bPool = IBPool(balancerPoolAddress);
for(uint256 i = 0; i < _tokens.length; i ++) {
IERC20 token = IERC20(_tokens[i]);
// Transfer tokens to this contract
token.transferFrom(msg.sender, address(this), _amounts[i]);
// Approve the balancer pool
token.approve(balancerPoolAddress, uint256(-1));
// Bind tokens
bPool.bind(_tokens[i], _amounts[i], _weights[i]);
}
bPool.setController(address(proxy));
// Setup smart pool
PCappedSmartPool smartPool = PCappedSmartPool(address(proxy));
smartPool.init(balancerPoolAddress, _name, _symbol, _initialSupply);
smartPool.setCap(_cap);
smartPool.setPublicSwapSetter(msg.sender);
smartPool.setTokenBinder(msg.sender);
smartPool.setController(msg.sender);
smartPool.approveTokens();
isPool[address(smartPool)] = true;
pools.push(address(smartPool));
emit SmartPoolCreated(address(smartPool), _name, _symbol);
smartPool.transfer(msg.sender, _initialSupply);
return address(smartPool);
}
}
// File contracts/interfaces/IUniswapFactory.sol
pragma solidity ^0.6.4;
interface IUniswapFactory {
// Create Exchange
function createExchange(address token) external returns (address exchange);
// Get Exchange and Token Info
function getExchange(address token) external view returns (address exchange);
function getToken(address exchange) external view returns (address token);
function getTokenWithId(uint256 tokenId) external view returns (address token);
// Never use
function initializeFactory(address template) external;
}
// File contracts/interfaces/IUniswapExchange.sol
pragma solidity ^0.6.4;
interface IUniswapExchange {
// Address of ERC20 token sold on this exchange
function tokenAddress() external view returns (address token);
// Address of Uniswap Factory
function factoryAddress() external view returns (address factory);
// Provide Liquidity
function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256);
function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256);
// Get Prices
function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256 tokens_bought);
function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256 eth_sold);
function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256 eth_bought);
function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256 tokens_sold);
// Trade ETH to ERC20
function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256 tokens_bought);
function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns (uint256 tokens_bought);
function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns (uint256 eth_sold);
function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256 eth_sold);
// Trade ERC20 to ETH
function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256 eth_bought);
function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256 eth_bought);
function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256 tokens_sold);
function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256 tokens_sold);
// Trade ERC20 to ERC20
function tokenToTokenSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_bought);
function tokenToTokenSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256 tokens_sold);
function tokenToTokenTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256 tokens_sold);
// Trade ERC20 to Custom Pool
function tokenToExchangeSwapInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeTransferInput(uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_bought);
function tokenToExchangeSwapOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256 tokens_sold);
function tokenToExchangeTransferOutput(uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256 tokens_sold);
// ERC20 comaptibility for liquidity tokens
// bytes32 public name;
// bytes32 public symbol;
// uint256 public decimals;
function transfer(address _to, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function allowance(address _owner, address _spender) external view returns (uint256);
function balanceOf(address _owner) external view returns (uint256);
function totalSupply() external view returns (uint256);
// Never use
function setup(address token_addr) external;
}
// File contracts/recipes/PUniswapPoolRecipe.sol
pragma solidity ^0.6.4;
// Takes ETH and mints smart pool tokens
contract PUniswapPoolRecipe {
bytes32 constant public uprSlot = keccak256("PUniswapPoolRecipe.storage.location");
// Uniswap pool recipe struct
struct uprs {
IPSmartPool pool;
IUniswapFactory uniswapFactory;
}
function init(address _pool, address _uniswapFactory) public virtual {
uprs storage s = luprs();
require(address(s.pool) == address(0), "already initialised");
s.pool = IPSmartPool(_pool);
s.uniswapFactory = IUniswapFactory(_uniswapFactory);
}
// Using same interface as Uniswap for compatibility
function ethToTokenTransferOutput(uint256 _tokens_bought, uint256 _deadline, address _recipient) public payable returns (uint256 eth_sold) {
uprs storage s = luprs();
require(_deadline >= block.timestamp);
(address[] memory tokens, uint256[] memory amounts) = s.pool.calcTokensForAmount(_tokens_bought);
eth_sold = 0;
// Buy and approve tokens
for(uint256 i = 0; i < tokens.length; i ++) {
eth_sold += _ethToToken(tokens[i], amounts[i]);
IERC20(tokens[i]).approve(address(s.pool), uint256(-1));
}
// Calculate amount of eth sold
eth_sold = msg.value - address(this).balance;
// Send back excess eth
msg.sender.transfer(address(this).balance);
// Join pool
s.pool.joinPool(_tokens_bought);
// Send pool tokens to receiver
s.pool.transfer(_recipient, s.pool.balanceOf(address(this)));
return eth_sold;
}
function ethToTokenSwapOutput(uint256 _tokens_bought, uint256 _deadline) external payable returns (uint256 eth_sold) {
return ethToTokenTransferOutput(_tokens_bought, _deadline, msg.sender);
}
function _ethToToken(address _token, uint256 _tokens_bought) internal virtual returns (uint256) {
uprs storage s = luprs();
IUniswapExchange exchange = IUniswapExchange(s.uniswapFactory.getExchange(_token));
return exchange.ethToTokenSwapOutput{value: address(this).balance}(_tokens_bought, uint256(-1));
}
function getEthToTokenOutputPrice(uint256 _tokens_bought) external view virtual returns (uint256 eth_sold) {
uprs storage s = luprs();
(address[] memory tokens, uint256[] memory amounts) = s.pool.calcTokensForAmount(_tokens_bought);
eth_sold = 0;
for(uint256 i = 0; i < tokens.length; i ++) {
IUniswapExchange exchange = IUniswapExchange(s.uniswapFactory.getExchange(tokens[i]));
eth_sold += exchange.getEthToTokenOutputPrice(amounts[i]);
}
return eth_sold;
}
function tokenToEthTransferInput(uint256 _tokens_sold, uint256 _min_eth, uint256 _deadline, address _recipient) public returns (uint256 eth_bought) {
uprs storage s = luprs();
require(_deadline >= block.timestamp);
require(s.pool.transferFrom(msg.sender, address(this), _tokens_sold), "PUniswapPoolRecipe.tokenToEthTransferInput: transferFrom failed");
s.pool.exitPool(_tokens_sold);
address[] memory tokens = s.pool.getTokens();
uint256 ethAmount = 0;
for(uint256 i = 0; i < tokens.length; i ++) {
IERC20 token = IERC20(tokens[i]);
uint256 balance = token.balanceOf(address(this));
// Exchange for ETH
ethAmount += _tokenToEth(token, balance, _recipient);
}
require(ethAmount > _min_eth, "PUniswapPoolRecipe.tokenToEthTransferInput: not enough ETH");
return ethAmount;
}
function tokenToEthSwapInput(uint256 _tokens_sold, uint256 _min_eth, uint256 _deadline) external returns (uint256 eth_bought) {
return tokenToEthTransferInput(_tokens_sold, _min_eth, _deadline, msg.sender);
}
function _tokenToEth(IERC20 _token, uint256 _tokens_sold, address _recipient) internal virtual returns (uint256 eth_bought) {
uprs storage s = luprs();
IUniswapExchange exchange = IUniswapExchange(s.uniswapFactory.getExchange(address(_token)));
_token.approve(address(exchange), _tokens_sold);
// Exchange for ETH
return exchange.tokenToEthTransferInput(_tokens_sold, 1, uint256(-1), _recipient);
}
function getTokenToEthInputPrice(uint256 _tokens_sold) external view virtual returns (uint256 eth_bought) {
uprs storage s = luprs();
(address[] memory tokens, uint256[] memory amounts) = s.pool.calcTokensForAmount(_tokens_sold);
eth_bought = 0;
for(uint256 i = 0; i < tokens.length; i ++) {
IUniswapExchange exchange = IUniswapExchange(s.uniswapFactory.getExchange(address(tokens[i])));
eth_bought += exchange.getTokenToEthInputPrice(amounts[i]);
}
return eth_bought;
}
function pool() external view returns (address) {
return address(luprs().pool);
}
receive() external payable {
}
// Load uniswap pool recipe
function luprs() internal pure returns (uprs storage s) {
bytes32 loc = uprSlot;
assembly {
s_slot := loc
}
}
}
// File contracts/interfaces/IKyberNetwork.sol
pragma solidity ^0.6.4;
interface IKyberNetwork {
function trade(
address src,
uint srcAmount,
address dest,
address payable destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
) external payable returns(uint256);
}
// File contracts/recipes/PUniswapKyberPoolRecipe.sol
pragma solidity ^0.6.4;
contract PUniswapKyberPoolRecipe is PUniswapPoolRecipe, Ownable {
bytes32 constant public ukprSlot = keccak256("PUniswapKyberPoolRecipe.storage.location");
// Uniswap pool recipe struct
struct ukprs {
mapping(address => bool) swapOnKyber;
IKyberNetwork kyber;
address feeReceiver;
}
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function init(address, address) public override {
require(false, "not enabled");
}
// Use seperate init function
function initUK(address _pool, address _uniswapFactory, address _kyber, address[] memory _swapOnKyber, address _feeReciever) public {
// UnsiwapRecipe enforces that init can only be called once
ukprs storage s = lukprs();
PUniswapPoolRecipe.init(_pool, _uniswapFactory);
s.kyber = IKyberNetwork(_kyber);
s.feeReceiver = _feeReciever;
_setOwner(msg.sender);
for(uint256 i = 0; i < _swapOnKyber.length; i ++) {
s.swapOnKyber[_swapOnKyber[i]] = true;
}
}
function setKyberSwap(address _token, bool _value) external onlyOwner {
ukprs storage s = lukprs();
s.swapOnKyber[_token] = _value;
}
function _ethToToken(address _token, uint256 _tokens_bought) internal override returns (uint256) {
ukprs storage s = lukprs();
if(!s.swapOnKyber[_token]) {
return super._ethToToken(_token, _tokens_bought);
}
uint256 ethBefore = address(this).balance;
s.kyber.trade{value: address(this).balance}(ETH, address(this).balance, _token, address(this), _tokens_bought, 1, s.feeReceiver);
uint256 ethAfter = address(this).balance;
// return amount of ETH spend
return ethBefore - ethAfter;
}
function _tokenToEth(IERC20 _token, uint256 _tokens_sold, address _recipient) internal override returns (uint256 eth_bought) {
ukprs storage s = lukprs();
if(!s.swapOnKyber[address(_token)]) {
return super._tokenToEth(_token, _tokens_sold, _recipient);
}
uint256 ethBefore = address(this).balance;
_token.approve(address(s.kyber), uint256(-1));
s.kyber.trade(address(_token), _tokens_sold, ETH, address(this), uint256(-1), 1, s.feeReceiver);
uint256 ethAfter = address(this).balance;
// return amount of ETH received
return ethAfter - ethBefore;
}
// Load uniswap pool recipe
function lukprs() internal pure returns (ukprs storage s) {
bytes32 loc = ukprSlot;
assembly {
s_slot := loc
}
}
}
// File contracts/test/TestReentryProtection.sol
pragma solidity ^0.6.4;
contract TestReentryProtection is ReentryProtection {
// This should fail
function test() external noReentry {
reenter();
}
function reenter() public noReentry {
// Do nothing
}
} | Load uniswap pool recipe | function lukprs() internal pure returns (ukprs storage s) {
bytes32 loc = ukprSlot;
assembly {
s_slot := loc
}
}
| 987,321 | [
1,
2563,
640,
291,
91,
438,
2845,
16100,
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,
328,
19445,
683,
87,
1435,
2713,
16618,
1135,
261,
19445,
683,
87,
2502,
272,
13,
288,
203,
3639,
1731,
1578,
1515,
273,
27178,
683,
8764,
31,
203,
3639,
19931,
288,
203,
5411,
272,
67,
14194,
519,
1515,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../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 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.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;
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/vesper/IVesperPool.sol";
import "./interfaces/aave/IAave.sol";
import "./interfaces/dydx/ISoloMargin.sol";
/**
* @title FlashLoanHelper:: This contract does all heavy lifting to get flash loan via Aave and DyDx.
* @dev End user has to override _flashLoanLogic() function to perform logic after flash loan is done.
* Also needs to approve token to aave and dydx via _approveToken function.
* 2 utility internal functions are also provided to activate/deactivate flash loan providers.
* Utility function are provided as internal so that end user can choose controlled access via public functions.
*/
abstract contract FlashLoanHelper {
using SafeERC20 for IERC20;
AaveLendingPoolAddressesProvider internal aaveAddressesProvider;
address internal constant SOLO = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
uint256 public dyDxMarketId;
bytes32 private constant AAVE_PROVIDER_ID = 0x0100000000000000000000000000000000000000000000000000000000000000;
bool public isAaveActive = false;
bool public isDyDxActive = false;
constructor(address _aaveAddressesProvider) {
require(_aaveAddressesProvider != address(0), "invalid-aave-provider");
aaveAddressesProvider = AaveLendingPoolAddressesProvider(_aaveAddressesProvider);
}
function _updateAaveStatus(bool _status) internal {
isAaveActive = _status;
}
function _updateDyDxStatus(bool _status, address _token) internal {
if (_status) {
dyDxMarketId = _getMarketIdFromTokenAddress(SOLO, _token);
}
isDyDxActive = _status;
}
/// @notice Approve all required tokens for flash loan
function _approveToken(address _token, uint256 _amount) internal {
IERC20(_token).safeApprove(SOLO, _amount);
IERC20(_token).safeApprove(aaveAddressesProvider.getLendingPool(), _amount);
}
/// @dev Override this function to execute logic which uses flash loan amount
function _flashLoanLogic(bytes memory _data, uint256 _repayAmount) internal virtual;
/***************************** Aave flash loan functions ***********************************/
bool private awaitingFlash = false;
/**
* @notice This is entry point for Aave flash loan
* @param _token Token for which we are taking flash loan
* @param _amountDesired Flash loan amount
* @param _data This will be passed downstream for processing. It can be empty.
*/
function _doAaveFlashLoan(
address _token,
uint256 _amountDesired,
bytes memory _data
) internal returns (uint256 _amount) {
require(isAaveActive, "aave-flash-loan-is-not-active");
AaveLendingPool _aaveLendingPool = AaveLendingPool(aaveAddressesProvider.getLendingPool());
AaveProtocolDataProvider _aaveProtocolDataProvider =
AaveProtocolDataProvider(aaveAddressesProvider.getAddress(AAVE_PROVIDER_ID));
// Check token liquidity in Aave
(uint256 _availableLiquidity, , , , , , , , , ) = _aaveProtocolDataProvider.getReserveData(_token);
if (_amountDesired > _availableLiquidity) {
_amountDesired = _availableLiquidity;
}
address[] memory assets = new address[](1);
assets[0] = _token;
uint256[] memory amounts = new uint256[](1);
amounts[0] = _amountDesired;
// 0 = no debt, 1 = stable, 2 = variable
uint256[] memory modes = new uint256[](1);
modes[0] = 0;
// Anyone can call aave flash loan to us, so we need some protection
awaitingFlash = true;
// function params: receiver, assets, amounts, modes, onBehalfOf, data, referralCode
_aaveLendingPool.flashLoan(address(this), assets, amounts, modes, address(this), _data, 0);
_amount = _amountDesired;
awaitingFlash = false;
}
/// @dev Aave will call this function after doing flash loan
function executeOperation(
address[] calldata, /*_assets*/
uint256[] calldata _amounts,
uint256[] calldata _premiums,
address _initiator,
bytes calldata _data
) external returns (bool) {
require(msg.sender == aaveAddressesProvider.getLendingPool(), "!aave-pool");
require(awaitingFlash, "invalid-flash-loan");
require(_initiator == address(this), "invalid-initiator");
// Flash loan amount + flash loan fee
uint256 _repayAmount = _amounts[0] + _premiums[0];
_flashLoanLogic(_data, _repayAmount);
return true;
}
/***************************** Aave flash loan functions ends ***********************************/
/***************************** DyDx flash loan functions ***************************************/
/**
* @notice This is entry point for DyDx flash loan
* @param _token Token for which we are taking flash loan
* @param _amountDesired Flash loan amount
* @param _data This will be passed downstream for processing. It can be empty.
*/
function _doDyDxFlashLoan(
address _token,
uint256 _amountDesired,
bytes memory _data
) internal returns (uint256 _amount) {
require(isDyDxActive, "dydx-flash-loan-is-not-active");
// Check token liquidity in DyDx
uint256 amountInSolo = IERC20(_token).balanceOf(SOLO);
if (_amountDesired > amountInSolo) {
_amountDesired = amountInSolo;
}
// Repay amount, amount with fee, can be 2 wei higher. Consider 2 wei as fee
uint256 repayAmount = _amountDesired + 2;
// Encode custom data for callFunction
bytes memory _callData = abi.encode(_data, repayAmount);
// 1. Withdraw _token
// 2. Call callFunction(...) which will call loanLogic
// 3. Deposit _token back
Actions.ActionArgs[] memory operations = new Actions.ActionArgs[](3);
operations[0] = _getWithdrawAction(dyDxMarketId, _amountDesired);
operations[1] = _getCallAction(_callData);
operations[2] = _getDepositAction(dyDxMarketId, repayAmount);
Account.Info[] memory accountInfos = new Account.Info[](1);
accountInfos[0] = _getAccountInfo();
ISoloMargin(SOLO).operate(accountInfos, operations);
_amount = _amountDesired;
}
/// @dev DyDx calls this function after doing flash loan
function callFunction(
address _sender,
Account.Info memory, /* _account */
bytes memory _callData
) external {
(bytes memory _data, uint256 _repayAmount) = abi.decode(_callData, (bytes, uint256));
require(msg.sender == SOLO, "!solo");
require(_sender == address(this), "invalid-initiator");
_flashLoanLogic(_data, _repayAmount);
}
/********************************* DyDx helper functions *********************************/
function _getAccountInfo() internal view returns (Account.Info memory) {
return Account.Info({owner: address(this), number: 1});
}
function _getMarketIdFromTokenAddress(address _solo, address token) internal view returns (uint256) {
ISoloMargin solo = ISoloMargin(_solo);
uint256 numMarkets = solo.getNumMarkets();
address curToken;
for (uint256 i = 0; i < numMarkets; i++) {
curToken = solo.getMarketTokenAddress(i);
if (curToken == token) {
return i;
}
}
revert("no-marketId-found-for-token");
}
function _getWithdrawAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Withdraw,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
function _getCallAction(bytes memory data) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Call,
accountId: 0,
amount: Types.AssetAmount({
sign: false,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: 0
}),
primaryMarketId: 0,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: data
});
}
function _getDepositAction(uint256 marketId, uint256 amount) internal view returns (Actions.ActionArgs memory) {
return
Actions.ActionArgs({
actionType: Actions.ActionType.Deposit,
accountId: 0,
amount: Types.AssetAmount({
sign: true,
denomination: Types.AssetDenomination.Wei,
ref: Types.AssetReference.Delta,
value: amount
}),
primaryMarketId: marketId,
secondaryMarketId: 0,
otherAddress: address(this),
otherAccountId: 0,
data: ""
});
}
/***************************** DyDx flash loan functions end *****************************/
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface AaveLendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
function getAddress(bytes32 id) external view returns (address);
}
interface AToken is IERC20 {
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (address);
}
interface AaveIncentivesController {
function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256);
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
}
interface AaveLendingPool {
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
}
interface AaveProtocolDataProvider {
function getReserveTokensAddresses(address asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
function getReserveData(address asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}
//solhint-disable func-name-mixedcase
interface StakedAave is IERC20 {
function claimRewards(address to, uint256 amount) external;
function cooldown() external;
function stake(address onBehalfOf, uint256 amount) external;
function redeem(address to, uint256 amount) external;
function getTotalRewardsBalance(address staker) external view returns (uint256);
function stakersCooldowns(address staker) external view returns (uint256);
function COOLDOWN_SECONDS() external view returns (uint256);
function UNSTAKE_WINDOW() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/* solhint-disable func-name-mixedcase */
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
interface ISwapManager {
event OracleCreated(address indexed _sender, address indexed _newOracle, uint256 _period);
function N_DEX() external view returns (uint256);
function ROUTERS(uint256 i) external view returns (IUniswapV2Router02);
function bestOutputFixedInput(
address _from,
address _to,
uint256 _amountIn
)
external
view
returns (
address[] memory path,
uint256 amountOut,
uint256 rIdx
);
function bestPathFixedInput(
address _from,
address _to,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function bestInputFixedOutput(
address _from,
address _to,
uint256 _amountOut
)
external
view
returns (
address[] memory path,
uint256 amountIn,
uint256 rIdx
);
function bestPathFixedOutput(
address _from,
address _to,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function safeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsOut(
uint256 _amountIn,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function safeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function unsafeGetAmountsIn(
uint256 _amountOut,
address[] memory _path,
uint256 _i
) external view returns (uint256[] memory result);
function comparePathsFixedInput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountIn,
uint256 _i
) external view returns (address[] memory path, uint256 amountOut);
function comparePathsFixedOutput(
address[] memory pathA,
address[] memory pathB,
uint256 _amountOut,
uint256 _i
) external view returns (address[] memory path, uint256 amountIn);
function ours(address a) external view returns (bool);
function oracleCount() external view returns (uint256);
function oracleAt(uint256 idx) external view returns (address);
function getOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external view returns (address);
function createOrUpdateOracle(
address _tokenA,
address _tokenB,
uint256 _period,
uint256 _i
) external returns (address oracleAddr);
function consultForFree(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
) external view returns (uint256 amountOut, uint256 lastUpdatedAt);
/// get the data we want and pay the gas to update
function consult(
address _from,
address _to,
uint256 _amountIn,
uint256 _period,
uint256 _i
)
external
returns (
uint256 amountOut,
uint256 lastUpdatedAt,
bool updated
);
function updateOracles() external returns (uint256 updated, uint256 expected);
function updateOracles(address[] memory _oracleAddrs) external returns (uint256 updated, uint256 expected);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface CToken {
function accrueInterest() external returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) external view returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrow(uint256 borrowAmount) external returns (uint256);
function mint() external payable; // For ETH
function mint(uint256 mintAmount) external returns (uint256); // For ERC20
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function repayBorrow() external payable; // For ETH
function repayBorrow(uint256 repayAmount) external returns (uint256); // For ERC20
function transfer(address user, uint256 amount) external returns (bool);
function getCash() external view returns (uint256);
function transferFrom(
address owner,
address user,
uint256 amount
) external returns (bool);
function underlying() external view returns (address);
}
interface Comptroller {
function claimComp(address holder, address[] memory) external;
function enterMarkets(address[] memory cTokens) external returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
function compAccrued(address holder) external view returns (uint256);
function getAccountLiquidity(address account)
external
view
returns (
uint256,
uint256,
uint256
);
function markets(address market)
external
view
returns (
bool isListed,
uint256 collateralFactorMantissa,
bool isCompted
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
/** In order to keep code/files short, all libraries and interfaces are trimmed as per Vesper need */
library Account {
enum Status {Normal, Liquid, Vapor}
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
}
library Actions {
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (publicly)
Sell, // sell an amount of some token (publicly)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
library Types {
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
}
interface ISoloMargin {
function getMarketTokenAddress(uint256 marketId) external view returns (address);
function getNumMarkets() external view returns (uint256);
function operate(Account.Info[] memory accounts, Actions.ActionArgs[] memory actions) external;
}
/**
* @title ICallee
* @author dYdX
*
* Interface that Callees for Solo must implement in order to ingest data.
*/
interface ICallee {
// ============ Public Functions ============
/**
* Allows users to send this contract arbitrary data.
*
* @param sender The msg.sender to Solo
* @param accountInfo The account from which the data is being sent
* @param data Arbitrary data given by the sender
*/
function callFunction(
address sender,
Account.Info memory accountInfo,
bytes memory data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
// Interface to use 3rd party Uniswap V3 oracle utility contract deployed at https://etherscan.io/address/0x0f1f5a87f99f0918e6c81f16e59f3518698221ff#code
/// @title UniswapV3 oracle with ability to query across an intermediate liquidity pool
interface IUniswapV3Oracle {
function assetToEth(
address _tokenIn,
uint256 _amountIn,
uint32 _twapPeriod
) external view returns (uint256 ethAmountOut);
function ethToAsset(
uint256 _ethAmountIn,
address _tokenOut,
uint32 _twapPeriod
) external view returns (uint256 amountOut);
function assetToAsset(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
uint32 _twapPeriod
) external view returns (uint256 amountOut);
function assetToAssetThruRoute(
address _tokenIn,
uint256 _amountIn,
address _tokenOut,
uint32 _twapPeriod,
address _routeThruToken,
uint24[2] memory _poolFees
) external view returns (uint256 amountOut);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface TokenLike is IERC20 {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
interface IStrategy {
function rebalance() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function feeCollector() external view returns (address);
function isReservedToken(address _token) external view returns (bool);
function keepers() external view returns (address[] memory);
function migrate(address _newStrategy) external;
function token() external view returns (address);
function totalValue() external view returns (uint256);
function totalValueCurrent() external returns (uint256);
function pool() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVesperPool is IERC20 {
function deposit() external payable;
function deposit(uint256 _share) external;
function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool);
function excessDebt(address _strategy) external view returns (uint256);
function permit(
address,
address,
uint256,
uint256,
uint8,
bytes32,
bytes32
) external;
function poolRewards() external returns (address);
function reportEarning(
uint256 _profit,
uint256 _loss,
uint256 _payback
) external;
function reportLoss(uint256 _loss) external;
function resetApproval() external;
function sweepERC20(address _fromToken) external;
function withdraw(uint256 _amount) external;
function withdrawETH(uint256 _amount) external;
function whitelistedWithdraw(uint256 _amount) external;
function governor() external view returns (address);
function keepers() external view returns (address[] memory);
function isKeeper(address _address) external view returns (bool);
function maintainers() external view returns (address[] memory);
function isMaintainer(address _address) external view returns (bool);
function feeCollector() external view returns (address);
function pricePerShare() external view returns (uint256);
function strategy(address _strategy)
external
view
returns (
bool _active,
uint256 _interestFee,
uint256 _debtRate,
uint256 _lastRebalance,
uint256 _totalDebt,
uint256 _totalLoss,
uint256 _totalProfit,
uint256 _debtRatio
);
function stopEverything() external view returns (bool);
function token() external view returns (IERC20);
function tokensHere() external view returns (uint256);
function totalDebtOf(address _strategy) external view returns (uint256);
function totalValue() external view returns (uint256);
function withdrawFee() external view returns (uint256);
// Function to get pricePerShare from V2 pools
function getPricePerShare() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "../dependencies/openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "../interfaces/bloq/ISwapManager.sol";
import "../interfaces/vesper/IStrategy.sol";
import "../interfaces/vesper/IVesperPool.sol";
abstract contract Strategy is IStrategy, Context {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint256 internal constant MAX_UINT_VALUE = type(uint256).max;
// solhint-disable-next-line var-name-mixedcase
address internal WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IERC20 public immutable collateralToken;
address public receiptToken;
address public immutable override pool;
address public override feeCollector;
ISwapManager public swapManager;
uint256 public oraclePeriod = 3600; // 1h
uint256 public oracleRouterIdx = 0; // Uniswap V2
uint256 public swapSlippage = 10000; // 100% Don't use oracles by default
EnumerableSet.AddressSet private _keepers;
event UpdatedFeeCollector(address indexed previousFeeCollector, address indexed newFeeCollector);
event UpdatedSwapManager(address indexed previousSwapManager, address indexed newSwapManager);
event UpdatedSwapSlippage(uint256 oldSwapSlippage, uint256 newSwapSlippage);
event UpdatedOracleConfig(uint256 oldPeriod, uint256 newPeriod, uint256 oldRouterIdx, uint256 newRouterIdx);
constructor(
address _pool,
address _swapManager,
address _receiptToken
) {
require(_pool != address(0), "pool-address-is-zero");
require(_swapManager != address(0), "sm-address-is-zero");
swapManager = ISwapManager(_swapManager);
pool = _pool;
collateralToken = IVesperPool(_pool).token();
receiptToken = _receiptToken;
require(_keepers.add(_msgSender()), "add-keeper-failed");
}
modifier onlyGovernor {
require(_msgSender() == IVesperPool(pool).governor(), "caller-is-not-the-governor");
_;
}
modifier onlyKeeper() {
require(_keepers.contains(_msgSender()), "caller-is-not-a-keeper");
_;
}
modifier onlyPool() {
require(_msgSender() == pool, "caller-is-not-vesper-pool");
_;
}
/**
* @notice Add given address in keepers list.
* @param _keeperAddress keeper address to add.
*/
function addKeeper(address _keeperAddress) external onlyGovernor {
require(_keepers.add(_keeperAddress), "add-keeper-failed");
}
/// @notice Return list of keepers
function keepers() external view override returns (address[] memory) {
return _keepers.values();
}
/**
* @notice Migrate all asset and vault ownership,if any, to new strategy
* @dev _beforeMigration hook can be implemented in child strategy to do extra steps.
* @param _newStrategy Address of new strategy
*/
function migrate(address _newStrategy) external virtual override onlyPool {
require(_newStrategy != address(0), "new-strategy-address-is-zero");
require(IStrategy(_newStrategy).pool() == pool, "not-valid-new-strategy");
_beforeMigration(_newStrategy);
IERC20(receiptToken).safeTransfer(_newStrategy, IERC20(receiptToken).balanceOf(address(this)));
collateralToken.safeTransfer(_newStrategy, collateralToken.balanceOf(address(this)));
}
/**
* @notice Remove given address from keepers list.
* @param _keeperAddress keeper address to remove.
*/
function removeKeeper(address _keeperAddress) external onlyGovernor {
require(_keepers.remove(_keeperAddress), "remove-keeper-failed");
}
/**
* @notice Update fee collector
* @param _feeCollector fee collector address
*/
function updateFeeCollector(address _feeCollector) external onlyGovernor {
require(_feeCollector != address(0), "fee-collector-address-is-zero");
require(_feeCollector != feeCollector, "fee-collector-is-same");
emit UpdatedFeeCollector(feeCollector, _feeCollector);
feeCollector = _feeCollector;
}
/**
* @notice Update swap manager address
* @param _swapManager swap manager address
*/
function updateSwapManager(address _swapManager) external onlyGovernor {
require(_swapManager != address(0), "sm-address-is-zero");
require(_swapManager != address(swapManager), "sm-is-same");
emit UpdatedSwapManager(address(swapManager), _swapManager);
swapManager = ISwapManager(_swapManager);
}
function updateSwapSlippage(uint256 _newSwapSlippage) external onlyGovernor {
require(_newSwapSlippage <= 10000, "invalid-slippage-value");
emit UpdatedSwapSlippage(swapSlippage, _newSwapSlippage);
swapSlippage = _newSwapSlippage;
}
function updateOracleConfig(uint256 _newPeriod, uint256 _newRouterIdx) external onlyGovernor {
require(_newRouterIdx < swapManager.N_DEX(), "invalid-router-index");
if (_newPeriod == 0) _newPeriod = oraclePeriod;
require(_newPeriod > 59, "invalid-oracle-period");
emit UpdatedOracleConfig(oraclePeriod, _newPeriod, oracleRouterIdx, _newRouterIdx);
oraclePeriod = _newPeriod;
oracleRouterIdx = _newRouterIdx;
}
/// @dev Approve all required tokens
function approveToken() external onlyKeeper {
_approveToken(0);
_approveToken(MAX_UINT_VALUE);
}
function setupOracles() external onlyKeeper {
_setupOracles();
}
/**
* @dev Withdraw collateral token from lending pool.
* @param _amount Amount of collateral token
*/
function withdraw(uint256 _amount) external override onlyPool {
_withdraw(_amount);
}
/**
* @dev Rebalance profit, loss and investment of this strategy
*/
function rebalance() external virtual override onlyKeeper {
(uint256 _profit, uint256 _loss, uint256 _payback) = _generateReport();
IVesperPool(pool).reportEarning(_profit, _loss, _payback);
_reinvest();
}
/**
* @dev sweep given token to feeCollector of strategy
* @param _fromToken token address to sweep
*/
function sweepERC20(address _fromToken) external override onlyKeeper {
require(feeCollector != address(0), "fee-collector-not-set");
require(_fromToken != address(collateralToken), "not-allowed-to-sweep-collateral");
require(!isReservedToken(_fromToken), "not-allowed-to-sweep");
if (_fromToken == ETH) {
Address.sendValue(payable(feeCollector), address(this).balance);
} else {
uint256 _amount = IERC20(_fromToken).balanceOf(address(this));
IERC20(_fromToken).safeTransfer(feeCollector, _amount);
}
}
/// @notice Returns address of token correspond to collateral token
function token() external view override returns (address) {
return receiptToken;
}
/**
* @notice Calculate total value of asset under management
* @dev Report total value in collateral token
*/
function totalValue() public view virtual override returns (uint256 _value);
/**
* @notice Calculate total value of asset under management (in real-time)
* @dev Report total value in collateral token
*/
function totalValueCurrent() external virtual override returns (uint256) {
return totalValue();
}
/// @notice Check whether given token is reserved or not. Reserved tokens are not allowed to sweep.
function isReservedToken(address _token) public view virtual override returns (bool);
/**
* @notice some strategy may want to prepare before doing migration.
Example In Maker old strategy want to give vault ownership to new strategy
* @param _newStrategy .
*/
function _beforeMigration(address _newStrategy) internal virtual;
/**
* @notice Generate report for current profit and loss. Also liquidate asset to payback
* excess debt, if any.
* @return _profit Calculate any realized profit and convert it to collateral, if not already.
* @return _loss Calculate any loss that strategy has made on investment. Convert into collateral token.
* @return _payback If strategy has any excess debt, we have to liquidate asset to payback excess debt.
*/
function _generateReport()
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _payback
)
{
uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this));
uint256 _totalDebt = IVesperPool(pool).totalDebtOf(address(this));
_profit = _realizeProfit(_totalDebt);
_loss = _realizeLoss(_totalDebt);
_payback = _liquidate(_excessDebt);
}
function _calcAmtOutAfterSlippage(uint256 _amount, uint256 _slippage) internal pure returns (uint256) {
return (_amount * (10000 - _slippage)) / (10000);
}
function _simpleOraclePath(address _from, address _to) internal view returns (address[] memory path) {
if (_from == WETH || _to == WETH) {
path = new address[](2);
path[0] = _from;
path[1] = _to;
} else {
path = new address[](3);
path[0] = _from;
path[1] = WETH;
path[2] = _to;
}
}
function _consultOracle(
address _from,
address _to,
uint256 _amt
) internal returns (uint256, bool) {
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
(bool _success, bytes memory _returnData) =
address(swapManager).call(
abi.encodePacked(swapManager.consult.selector, abi.encode(_from, _to, _amt, oraclePeriod, i))
);
if (_success) {
(uint256 rate, uint256 lastUpdate, ) = abi.decode(_returnData, (uint256, uint256, bool));
if ((lastUpdate > (block.timestamp - oraclePeriod)) && (rate != 0)) return (rate, true);
return (0, false);
}
}
return (0, false);
}
function _getOracleRate(address[] memory path, uint256 _amountIn) internal returns (uint256 amountOut) {
require(path.length > 1, "invalid-oracle-path");
amountOut = _amountIn;
bool isValid;
for (uint256 i = 0; i < path.length - 1; i++) {
(amountOut, isValid) = _consultOracle(path[i], path[i + 1], amountOut);
require(isValid, "invalid-oracle-rate");
}
}
/**
* @notice Safe swap via Uniswap / Sushiswap (better rate of the two)
* @dev There are many scenarios when token swap via Uniswap can fail, so this
* method will wrap Uniswap call in a 'try catch' to make it fail safe.
* however, this method will throw minAmountOut is not met
* @param _from address of from token
* @param _to address of to token
* @param _amountIn Amount to be swapped
* @param _minAmountOut minimum amount out
*/
function _safeSwap(
address _from,
address _to,
uint256 _amountIn,
uint256 _minAmountOut
) internal {
(address[] memory path, uint256 amountOut, uint256 rIdx) =
swapManager.bestOutputFixedInput(_from, _to, _amountIn);
if (_minAmountOut == 0) _minAmountOut = 1;
if (amountOut != 0) {
swapManager.ROUTERS(rIdx).swapExactTokensForTokens(
_amountIn,
_minAmountOut,
path,
address(this),
block.timestamp
);
}
}
// These methods can be implemented by the inheriting strategy.
/* solhint-disable no-empty-blocks */
function _claimRewardsAndConvertTo(address _toToken) internal virtual {}
/**
* @notice Set up any oracles that are needed for this strategy.
*/
function _setupOracles() internal virtual {}
/* solhint-enable */
// These methods must be implemented by the inheriting strategy
function _withdraw(uint256 _amount) internal virtual;
function _approveToken(uint256 _amount) internal virtual;
/**
* @notice Withdraw collateral to payback excess debt in pool.
* @param _excessDebt Excess debt of strategy in collateral token
* @return _payback amount in collateral token. Usually it is equal to excess debt.
*/
function _liquidate(uint256 _excessDebt) internal virtual returns (uint256 _payback);
/**
* @notice Calculate earning and withdraw/convert it into collateral token.
* @param _totalDebt Total collateral debt of this strategy
* @return _profit Profit in collateral token
*/
function _realizeProfit(uint256 _totalDebt) internal virtual returns (uint256 _profit);
/**
* @notice Calculate loss
* @param _totalDebt Total collateral debt of this strategy
* @return _loss Realized loss in collateral token
*/
function _realizeLoss(uint256 _totalDebt) internal virtual returns (uint256 _loss);
/**
* @notice Reinvest collateral.
* @dev Once we file report back in pool, we might have some collateral in hand
* which we want to reinvest aka deposit in lender/provider.
*/
function _reinvest() internal virtual;
}
// SPDX-License-Identifier: GNU LGPLv3
// Heavily inspired from CompoundLeverage strategy of Yearn. https://etherscan.io/address/0x4031afd3B0F71Bace9181E554A9E680Ee4AbE7dF#code
pragma solidity 0.8.3;
import "../Strategy.sol";
import "../../interfaces/compound/ICompound.sol";
import "../../interfaces/oracle/IUniswapV3Oracle.sol";
import "../../FlashLoanHelper.sol";
/// @title This strategy will deposit collateral token in Compound and based on position
/// it will borrow same collateral token. It will use borrowed asset as supply and borrow again.
contract CompoundLeverageStrategy is Strategy, FlashLoanHelper {
using SafeERC20 for IERC20;
// solhint-disable-next-line var-name-mixedcase
string public NAME;
string public constant VERSION = "4.0.0";
uint256 internal constant MAX_BPS = 10_000; //100%
uint256 public minBorrowRatio = 5_000; // 50%
uint256 public maxBorrowRatio = 6_000; // 60%
CToken internal cToken;
IUniswapV3Oracle internal constant ORACLE = IUniswapV3Oracle(0x0F1f5A87f99f0918e6C81F16E59F3518698221Ff);
uint32 internal constant TWAP_PERIOD = 3600;
Comptroller public immutable comptroller;
address public immutable rewardToken;
address public rewardDistributor;
event UpdatedBorrowRatio(
uint256 previousMinBorrowRatio,
uint256 newMinBorrowRatio,
uint256 previousMaxBorrowRatio,
uint256 newMaxBorrowRatio
);
constructor(
address _pool,
address _swapManager,
address _comptroller,
address _rewardDistributor,
address _rewardToken,
address _aaveAddressesProvider,
address _receiptToken,
string memory _name
) Strategy(_pool, _swapManager, _receiptToken) FlashLoanHelper(_aaveAddressesProvider) {
NAME = _name;
require(_comptroller != address(0), "comptroller-address-is-zero");
comptroller = Comptroller(_comptroller);
rewardToken = _rewardToken;
require(_receiptToken != address(0), "cToken-address-is-zero");
cToken = CToken(_receiptToken);
require(_rewardDistributor != address(0), "invalid-reward-distributor-addr");
rewardDistributor = _rewardDistributor;
}
/**
* @notice Update upper and lower borrow ratio
* @dev It is possible to set 0 as _minBorrowRatio to not borrow anything
* @param _minBorrowRatio Minimum % we want to borrow
* @param _maxBorrowRatio Maximum % we want to borrow
*/
function updateBorrowRatio(uint256 _minBorrowRatio, uint256 _maxBorrowRatio) external onlyGovernor {
(, uint256 _collateralFactor, ) = comptroller.markets(address(cToken));
require(_maxBorrowRatio < (_collateralFactor / 1e14), "invalid-max-borrow-limit");
require(_maxBorrowRatio > _minBorrowRatio, "max-should-be-higher-than-min");
emit UpdatedBorrowRatio(minBorrowRatio, _minBorrowRatio, maxBorrowRatio, _maxBorrowRatio);
minBorrowRatio = _minBorrowRatio;
maxBorrowRatio = _maxBorrowRatio;
}
function updateAaveStatus(bool _status) external onlyGovernor {
_updateAaveStatus(_status);
}
function updateDyDxStatus(bool _status) external virtual onlyGovernor {
_updateDyDxStatus(_status, address(collateralToken));
}
/**
* @notice Calculate total value based on rewardToken claimed, supply and borrow position
* @dev Report total value in collateral token
* @dev Claimed rewardToken will stay in strategy until next rebalance
*/
function totalValueCurrent() public override returns (uint256 _totalValue) {
cToken.exchangeRateCurrent();
_claimRewards();
_totalValue = _calculateTotalValue(IERC20(rewardToken).balanceOf(address(this)));
}
/**
* @notice Current borrow ratio, calculated as current borrow divide by max allowed borrow
* Return value is based on basis points, i.e. 7500 = 75% ratio
*/
function currentBorrowRatio() external view returns (uint256) {
(uint256 _supply, uint256 _borrow) = getPosition();
return _borrow == 0 ? 0 : (_borrow * MAX_BPS) / _supply;
}
/**
* @notice Calculate total value using rewardToken accrued, supply and borrow position
* @dev Compound calculate rewardToken accrued and store it when user interact with
* Compound contracts, i.e. deposit, withdraw or transfer tokens.
* So compAccrued() will return stored rewardToken accrued amount, which is older
* @dev For up to date value check totalValueCurrent()
*/
function totalValue() public view virtual override returns (uint256 _totalValue) {
_totalValue = _calculateTotalValue(_getRewardAccrued());
}
/**
* @notice Calculate current position using claimed rewardToken and current borrow.
*/
function isLossMaking() external returns (bool) {
// It's loss making if _totalValue < totalDebt
return totalValueCurrent() < IVesperPool(pool).totalDebtOf(address(this));
}
function isReservedToken(address _token) public view virtual override returns (bool) {
return _token == address(cToken) || _token == rewardToken || _token == address(collateralToken);
}
/// @notice Return supply and borrow position. Position may return few block old value
function getPosition() public view returns (uint256 _supply, uint256 _borrow) {
(, uint256 _cTokenBalance, uint256 _borrowBalance, uint256 _exchangeRate) =
cToken.getAccountSnapshot(address(this));
_supply = (_cTokenBalance * _exchangeRate) / 1e18;
_borrow = _borrowBalance;
}
/// @notice Approve all required tokens
function _approveToken(uint256 _amount) internal virtual override {
collateralToken.safeApprove(pool, _amount);
collateralToken.safeApprove(address(cToken), _amount);
for (uint256 i = 0; i < swapManager.N_DEX(); i++) {
IERC20(rewardToken).safeApprove(address(swapManager.ROUTERS(i)), _amount);
}
FlashLoanHelper._approveToken(address(collateralToken), _amount);
}
/**
* @notice Claim rewardToken and transfer to new strategy
* @param _newStrategy Address of new strategy.
*/
function _beforeMigration(address _newStrategy) internal virtual override {
require(IStrategy(_newStrategy).token() == address(cToken), "wrong-receipt-token");
minBorrowRatio = 0;
// It will calculate amount to repay based on borrow limit and payback all
_reinvest();
}
/**
* @notice Calculate borrow position based on borrow ratio, current supply, borrow, amount
* being deposited or withdrawn.
* @param _amount Collateral amount
* @param _isDeposit Flag indicating whether we are depositing _amount or withdrawing
* @return _position Amount of borrow that need to be adjusted
* @return _shouldRepay Flag indicating whether _position is borrow amount or repay amount
*/
function _calculateDesiredPosition(uint256 _amount, bool _isDeposit)
internal
returns (uint256 _position, bool _shouldRepay)
{
uint256 _totalSupply = cToken.balanceOfUnderlying(address(this));
uint256 _currentBorrow = cToken.borrowBalanceStored(address(this));
// If minimum borrow limit set to 0 then repay borrow
if (minBorrowRatio == 0) {
return (_currentBorrow, true);
}
uint256 _supply = _totalSupply - _currentBorrow;
// In case of withdraw, _amount can be greater than _supply
uint256 _newSupply = _isDeposit ? _supply + _amount : _supply > _amount ? _supply - _amount : 0;
// (supply * borrowRatio)/(BPS - borrowRatio)
uint256 _borrowUpperBound = (_newSupply * maxBorrowRatio) / (MAX_BPS - maxBorrowRatio);
uint256 _borrowLowerBound = (_newSupply * minBorrowRatio) / (MAX_BPS - minBorrowRatio);
// If our current borrow is greater than max borrow allowed, then we will have to repay
// some to achieve safe position else borrow more.
if (_currentBorrow > _borrowUpperBound) {
_shouldRepay = true;
// If borrow > upperBound then it is greater than lowerBound too.
_position = _currentBorrow - _borrowLowerBound;
} else if (_currentBorrow < _borrowLowerBound) {
_shouldRepay = false;
// We can borrow more.
_position = _borrowLowerBound - _currentBorrow;
}
}
/// @notice Get main Rewards accrued
function _getRewardAccrued() internal view virtual returns (uint256 _rewardAccrued) {
_rewardAccrued = comptroller.compAccrued(address(this));
}
/**
* @dev rewardToken is converted to collateral and if we have some borrow interest to pay,
* it will go come from collateral.
* @dev Report total value in collateral token
*/
function _calculateTotalValue(uint256 _rewardAccrued) internal view returns (uint256 _totalValue) {
uint256 _compAsCollateral;
if (_rewardAccrued != 0) {
(, _compAsCollateral, ) = swapManager.bestOutputFixedInput(
rewardToken,
address(collateralToken),
_rewardAccrued
);
}
(uint256 _supply, uint256 _borrow) = getPosition();
_totalValue = _compAsCollateral + collateralToken.balanceOf(address(this)) + _supply - _borrow;
}
/// @notice Claim comp
function _claimRewards() internal virtual {
address[] memory _markets = new address[](1);
_markets[0] = address(cToken);
comptroller.claimComp(address(this), _markets);
}
/// @notice Claim rewardToken and convert rewardToken into collateral token.
function _claimRewardsAndConvertTo(address _toToken) internal override {
_claimRewards();
uint256 _rewardAmount = IERC20(rewardToken).balanceOf(address(this));
if (_rewardAmount != 0) {
_safeSwap(rewardToken, _toToken, _rewardAmount);
}
}
/**
* @notice Generate report for pools accounting and also send profit and any payback to pool.
* @dev Claim rewardToken and convert to collateral.
*/
function _generateReport()
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _payback
)
{
uint256 _excessDebt = IVesperPool(pool).excessDebt(address(this));
(, , , , uint256 _totalDebt, , , uint256 _debtRatio) = IVesperPool(pool).strategy(address(this));
// Claim rewardToken and convert to collateral token
_claimRewardsAndConvertTo(address(collateralToken));
uint256 _supply = cToken.balanceOfUnderlying(address(this));
uint256 _borrow = cToken.borrowBalanceStored(address(this));
uint256 _investedCollateral = _supply - _borrow;
uint256 _collateralHere = collateralToken.balanceOf(address(this));
uint256 _totalCollateral = _investedCollateral + _collateralHere;
uint256 _profitToWithdraw;
if (_totalCollateral > _totalDebt) {
_profit = _totalCollateral - _totalDebt;
if (_collateralHere <= _profit) {
_profitToWithdraw = _profit - _collateralHere;
} else if (_collateralHere >= (_profit + _excessDebt)) {
_payback = _excessDebt;
} else {
// _profit < CollateralHere < _profit + _excessDebt
_payback = _collateralHere - _profit;
}
} else {
_loss = _totalDebt - _totalCollateral;
}
uint256 _paybackToWithdraw = _excessDebt - _payback;
uint256 _totalAmountToWithdraw = _paybackToWithdraw + _profitToWithdraw;
if (_totalAmountToWithdraw != 0) {
uint256 _withdrawn = _withdrawHere(_totalAmountToWithdraw);
// Any amount withdrawn over _profitToWithdraw is payback for pool
if (_withdrawn > _profitToWithdraw) {
_payback += (_withdrawn - _profitToWithdraw);
}
}
// Handle scenario if debtRatio is zero and some supply left.
// Remaining tokens, after payback withdrawal, are profit
(_supply, _borrow) = getPosition();
if (_debtRatio == 0 && _supply != 0 && _borrow == 0) {
// This will redeem all cTokens this strategy has
_redeemUnderlying(MAX_UINT_VALUE);
_profit += _supply;
}
}
/**
* Adjust position by normal leverage and deleverage.
* @param _adjustBy Amount by which we want to increase or decrease _borrow
* @param _shouldRepay True indicate we want to deleverage
* @return amount Actual adjusted amount
*/
function _adjustPosition(uint256 _adjustBy, bool _shouldRepay) internal returns (uint256 amount) {
// We can get position via view function, as this function will be called after _calculateDesiredPosition
(uint256 _supply, uint256 _borrow) = getPosition();
// If no borrow then there is nothing to deleverage
if (_borrow == 0 && _shouldRepay) {
return 0;
}
(, uint256 collateralFactor, ) = comptroller.markets(address(cToken));
if (_shouldRepay) {
amount = _normalDeleverage(_adjustBy, _supply, _borrow, collateralFactor);
} else {
amount = _normalLeverage(_adjustBy, _supply, _borrow, collateralFactor);
}
}
/**
* Deleverage: Reduce borrow to achieve safe position
* @param _maxDeleverage Reduce borrow by this amount
* @return _deleveragedAmount Amount we actually reduced
*/
function _normalDeleverage(
uint256 _maxDeleverage,
uint256 _supply,
uint256 _borrow,
uint256 _collateralFactor
) internal returns (uint256 _deleveragedAmount) {
uint256 _theoreticalSupply;
if (_collateralFactor != 0) {
// Calculate minimum supply required to support _borrow
_theoreticalSupply = (_borrow * 1e18) / _collateralFactor;
}
_deleveragedAmount = _supply - _theoreticalSupply;
if (_deleveragedAmount >= _borrow) {
_deleveragedAmount = _borrow;
}
if (_deleveragedAmount >= _maxDeleverage) {
_deleveragedAmount = _maxDeleverage;
}
_redeemUnderlying(_deleveragedAmount);
_repayBorrow(_deleveragedAmount);
}
/**
* Leverage: Borrow more
* @param _maxLeverage Max amount to borrow
* @return _leveragedAmount Amount we actually borrowed
*/
function _normalLeverage(
uint256 _maxLeverage,
uint256 _supply,
uint256 _borrow,
uint256 _collateralFactor
) internal returns (uint256 _leveragedAmount) {
// Calculate maximum we can borrow at current _supply
uint256 theoreticalBorrow = (_supply * _collateralFactor) / 1e18;
_leveragedAmount = theoreticalBorrow - _borrow;
if (_leveragedAmount >= _maxLeverage) {
_leveragedAmount = _maxLeverage;
}
_borrowCollateral(_leveragedAmount);
_mint(collateralToken.balanceOf(address(this)));
}
/// @notice Deposit collateral in Compound and adjust borrow position
function _reinvest() internal virtual override {
uint256 _collateralBalance = collateralToken.balanceOf(address(this));
(uint256 _position, bool _shouldRepay) = _calculateDesiredPosition(_collateralBalance, true);
// Supply collateral to compound.
_mint(_collateralBalance);
// During reinvest, _shouldRepay will be false which indicate that we will borrow more.
_position -= _doFlashLoan(_position, _shouldRepay);
uint256 i = 0;
while (_position > 0 && i <= 6) {
_position -= _adjustPosition(_position, _shouldRepay);
i++;
}
}
/// @dev Withdraw collateral and transfer it to pool
function _withdraw(uint256 _amount) internal override {
collateralToken.safeTransfer(pool, _withdrawHere(_amount));
}
/// @dev Withdraw collateral here. Do not transfer to pool
function _withdrawHere(uint256 _amount) internal returns (uint256) {
(uint256 _position, bool _shouldRepay) = _calculateDesiredPosition(_amount, false);
if (_shouldRepay) {
// Do deleverage by flash loan
_position -= _doFlashLoan(_position, _shouldRepay);
// If we still have _position to deleverage do it via normal deleverage
uint256 i = 0;
while (_position > 0 && i <= 10) {
_position -= _adjustPosition(_position, true);
i++;
}
// There may be scenario where we are not able to deleverage enough
if (_position != 0) {
// Calculate redeemable at current borrow and supply.
(uint256 _supply, uint256 _borrow) = getPosition();
uint256 _supplyToSupportBorrow;
if (maxBorrowRatio != 0) {
_supplyToSupportBorrow = (_borrow * MAX_BPS) / maxBorrowRatio;
}
// Current supply minus supply required to support _borrow at _maxBorrowRatio
uint256 _redeemable = _supply - _supplyToSupportBorrow;
if (_amount > _redeemable) {
_amount = _redeemable;
}
}
}
uint256 _collateralBefore = collateralToken.balanceOf(address(this));
// If we do not have enough collateral, try to get some via COMP
// This scenario is rare and will happen during last withdraw
if (_amount > cToken.balanceOfUnderlying(address(this))) {
// Use all collateral for withdraw
_collateralBefore = 0;
_claimRewardsAndConvertTo(address(collateralToken));
// Updated amount
_amount = _amount - collateralToken.balanceOf(address(this));
}
_redeemUnderlying(_amount);
uint256 _collateralAfter = collateralToken.balanceOf(address(this));
return _collateralAfter - _collateralBefore;
}
/**
* @dev Aave flash is used only for withdrawal due to high fee compare to DyDx
* @param _flashAmount Amount for flash loan
* @param _shouldRepay Flag indicating we want to leverage or deleverage
* @return Total amount we leverage or deleverage using flash loan
*/
function _doFlashLoan(uint256 _flashAmount, bool _shouldRepay) internal returns (uint256) {
uint256 _totalFlashAmount;
// Due to less fee DyDx is our primary flash loan provider
if (isDyDxActive && _flashAmount > 0) {
bytes memory _data = abi.encode(_flashAmount, _shouldRepay);
_totalFlashAmount = _doDyDxFlashLoan(address(collateralToken), _flashAmount, _data);
_flashAmount -= _totalFlashAmount;
}
if (isAaveActive && _shouldRepay && _flashAmount > 0) {
bytes memory _data = abi.encode(_flashAmount, _shouldRepay);
_totalFlashAmount += _doAaveFlashLoan(address(collateralToken), _flashAmount, _data);
}
return _totalFlashAmount;
}
/**
* @notice This function will be called by flash loan
* @dev In case of borrow, DyDx is preferred as fee is so low that it does not effect
* our collateralRatio and liquidation risk.
*/
function _flashLoanLogic(bytes memory _data, uint256 _repayAmount) internal override {
(uint256 _amount, bool _deficit) = abi.decode(_data, (uint256, bool));
uint256 _collateralHere = collateralToken.balanceOf(address(this));
require(_collateralHere >= _amount, "FLASH_FAILED"); // to stop malicious calls
//if in deficit we repay amount and then withdraw
if (_deficit) {
_repayBorrow(_amount);
//if we are withdrawing we take more to cover fee
_redeemUnderlying(_repayAmount);
} else {
_mint(_collateralHere);
//borrow more to cover fee
_borrowCollateral(_repayAmount);
}
}
/**
* @dev If swap slippage is defined then use oracle to get amountOut and calculate minAmountOut
*/
function _safeSwap(
address _tokenIn,
address _tokenOut,
uint256 _amountIn
) internal virtual {
uint256 _minAmountOut =
swapSlippage != 10000
? _calcAmtOutAfterSlippage(
ORACLE.assetToAsset(_tokenIn, _amountIn, _tokenOut, TWAP_PERIOD),
swapSlippage
)
: 1;
_safeSwap(_tokenIn, _tokenOut, _amountIn, _minAmountOut);
}
//////////////////// Compound wrapper functions //////////////////////////////
/**
* @dev Compound support ETH as collateral not WETH. So ETH strategy can override
* below functions and handle wrap/unwrap of WETH.
*/
function _mint(uint256 _amount) internal virtual {
require(cToken.mint(_amount) == 0, "supply-to-compound-failed");
}
function _redeemUnderlying(uint256 _amount) internal virtual {
if (_amount == MAX_UINT_VALUE) {
// Withdraw all cTokens
require(cToken.redeem(cToken.balanceOf(address(this))) == 0, "withdraw-from-compound-failed");
} else {
// Withdraw underlying
require(cToken.redeemUnderlying(_amount) == 0, "withdraw-from-compound-failed");
}
}
function _borrowCollateral(uint256 _amount) internal virtual {
require(cToken.borrow(_amount) == 0, "borrow-from-compound-failed");
}
function _repayBorrow(uint256 _amount) internal virtual {
require(cToken.repayBorrow(_amount) == 0, "repay-to-compound-failed");
}
//////////////////////////////////////////////////////////////////////////////
/* solhint-disable no-empty-blocks */
// We overridden _generateReport which eliminates need of below function.
function _liquidate(uint256 _excessDebt) internal override returns (uint256 _payback) {}
function _realizeProfit(uint256 _totalDebt) internal virtual override returns (uint256) {}
function _realizeLoss(uint256 _totalDebt) internal view override returns (uint256 _loss) {}
/* solhint-enable no-empty-blocks */
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.3;
import "./CompoundLeverageStrategy.sol";
import "../../interfaces/token/IToken.sol";
// solhint-disable no-empty-blocks
/// @title Deposit ETH in Compound and earn interest.
contract CompoundLeverageStrategyETH is CompoundLeverageStrategy {
constructor(
address _pool,
address _swapManager,
address _comptroller,
address _rewardDistributor,
address _rewardToken,
address _aaveAddressesProvider,
address _receiptToken,
string memory _name
)
CompoundLeverageStrategy(
_pool,
_swapManager,
_comptroller,
_rewardDistributor,
_rewardToken,
_aaveAddressesProvider,
_receiptToken,
_name
)
{}
/// @dev Only receive ETH from either cToken or WETH
receive() external payable {
require(msg.sender == address(cToken) || msg.sender == WETH, "not-allowed-to-send-ether");
}
/// @dev Compound support ETH as collateral. Convert WETH to ETH and mint cETH
function _mint(uint256 _amount) internal override {
_withdrawETH(_amount);
cToken.mint{value: _amount}();
}
/// @dev On redeem we will receive ETH. Convert received ETH into WETH
function _redeemUnderlying(uint256 _amount) internal override {
super._redeemUnderlying(_amount);
_depositETH();
}
/// @dev On borrow we will receive ETH. Convert received ETH into WETH
function _borrowCollateral(uint256 _amount) internal override {
super._borrowCollateral(_amount);
_depositETH();
}
/// @dev Repay will take ETH. Convert WETH to ETH and call payable repay function
function _repayBorrow(uint256 _amount) internal override {
_withdrawETH(_amount);
cToken.repayBorrow{value: _amount}();
}
/// @dev Deposit ETH and get WETH in return
function _depositETH() internal {
TokenLike(WETH).deposit{value: address(this).balance}();
}
/// @dev Withdraw ETH by burning similar amount of WETH
function _withdrawETH(uint256 _amount) internal {
TokenLike(WETH).withdraw(_amount);
}
} | * @notice Current borrow ratio, calculated as current borrow divide by max allowed borrow Return value is based on basis points, i.e. 7500 = 75% ratio/ | function currentBorrowRatio() external view returns (uint256) {
(uint256 _supply, uint256 _borrow) = getPosition();
return _borrow == 0 ? 0 : (_borrow * MAX_BPS) / _supply;
}
| 1,539,081 | [
1,
3935,
29759,
7169,
16,
8894,
487,
783,
29759,
12326,
635,
943,
2935,
29759,
2000,
460,
353,
2511,
603,
10853,
3143,
16,
277,
18,
73,
18,
2371,
12483,
273,
18821,
9,
7169,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
783,
38,
15318,
8541,
1435,
3903,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
261,
11890,
5034,
389,
2859,
1283,
16,
2254,
5034,
389,
70,
15318,
13,
273,
14441,
5621,
203,
3639,
327,
389,
70,
15318,
422,
374,
692,
374,
294,
261,
67,
70,
15318,
380,
4552,
67,
38,
5857,
13,
342,
389,
2859,
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,
-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;
contract CrypticLegendsToken {
address private _owner;
uint8 private constant levelDefault = 5;
uint8 private constant levelMax = 20;
//median value is used to restrict the median value of abilities given. Also this is the default value
uint8 private constant levelMedian = 12;
uint8 private tokenCount = 0;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
/**
Name
String containing the hero's name.
Core Attributes
Core attributes can have an integer value from the interval [5, 20].
Wisdom (WIS)
Bonus to mental defense and mental effect potency.
Intelligence (INT)
Bonus to certain mental actions’ success.
Charisma (CHA)
Bonus to certain mental actions’ success.
Speed (SPD)
Lowers the duration of performing actions.
Accuracy (ACC)
Bonus to physical actions’ success.
Might (MGT)
Determines hero’s maximum health and gives bonus to physical effect potency.
*/
//Main Character object definition
struct Character {
string name;
uint8 wisdom;
uint8 inteligence;
uint8 charisma;
uint8 speed;
uint8 accuracy;
uint8 might;
}
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
mapping(uint256 => Character) public tokenProperty;
//EVENTS
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event Transfer(address from, address to, uint256 tokenId);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () public {
_owner = msg.sender;
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address _tmpOwner = _tokenOwner[tokenId];
return _tmpOwner != address(0);
}
/**
* @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) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address _tmpOwner = ownerOf(tokenId);
return (spender == _tmpOwner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
//MODIFIERS
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
* @notice Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/** Ownable end */
/**
* @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) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
/**
* @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 memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address _tmpOwner = _tokenOwner[tokenId];
require(_tmpOwner != address(0), "ERC721: owner query for nonexistent token");
return _tmpOwner;
}
/**
* @dev Gets the balance of the specified address.
* @param _tmpOwner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _tmpOwner) public view returns (uint256) {
require(_tmpOwner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[_tmpOwner];
}
modifier levelInRange(uint _level) {
require(_level <= levelMax && _level >= levelDefault , 'Level not in range');
_;
}
/**
* @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
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to] += 1;
emit Transfer(address(0), to, tokenId);
}
function mintCharacter(address _to, string memory _name, uint8 _wisdom, uint8 _inteligence
, uint8 _charisma, uint8 _speed, uint8 _accuracy, uint8 _might)
public
onlyOwner
returns(bool) {
tokenCount += 1;
tokenProperty[tokenCount] = Character({
name: _name,
wisdom: _wisdom,
inteligence: _inteligence,
charisma: _charisma,
speed: _speed,
accuracy: _accuracy,
might: _might
});
_mint(_to, tokenCount);
return true;
}
function mint(address _to, string memory _name) public onlyOwner returns(bool) {
return mintCharacter(_to, _name, levelDefault, levelDefault, levelDefault, levelDefault, levelDefault, levelDefault);
}
function getToken(uint _tokenId) public view returns(string memory, uint8, uint8, uint8, uint8, uint8, uint8) {
return (tokenProperty[_tokenId].name
, tokenProperty[_tokenId].wisdom
, tokenProperty[_tokenId].inteligence
, tokenProperty[_tokenId].charisma
, tokenProperty[_tokenId].speed
, tokenProperty[_tokenId].accuracy
, tokenProperty[_tokenId].might
);
}
/**
* @dev Returns total amount of toknes minted
*
*/
function getTokenCount() public view returns(uint8) {
return tokenCount;
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @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) internal {
require(ownerOf(tokenId) == from, "transfer of token that is not own");
require(to != address(0), "transfer to the zero address");
_ownedTokensCount[from] -= 1;
_ownedTokensCount[to] += 1;
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @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 {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner");
_transferFrom(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 {
transferFrom(from, to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param _tmpOwner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address _tmpOwner, uint256 tokenId) internal {
require(ownerOf(tokenId) == _tmpOwner, "burn of token that is not own");
_ownedTokensCount[_tmpOwner] -= 1;
_tokenOwner[tokenId] = address(0);
emit Transfer(_tmpOwner, address(0), 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
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
}
| * @dev Allows the current owner to relinquish control of the contract. It will not be possible to call the functions with the `onlyOwner` modifier anymore. @notice Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner./ | function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
| 886,124 | [
1,
19132,
326,
783,
3410,
358,
1279,
267,
372,
1468,
3325,
434,
326,
6835,
18,
2597,
903,
486,
506,
3323,
358,
745,
326,
4186,
598,
326,
1375,
3700,
5541,
68,
9606,
16828,
18,
225,
25921,
465,
2822,
23178,
903,
8851,
326,
6835,
2887,
392,
3410,
16,
1915,
1637,
9427,
1281,
14176,
716,
353,
1338,
2319,
358,
326,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
225,
445,
1654,
8386,
5460,
12565,
1435,
1071,
1338,
5541,
288,
203,
1377,
3626,
14223,
9646,
5310,
1429,
4193,
24899,
8443,
16,
1758,
12,
20,
10019,
203,
1377,
389,
8443,
273,
1758,
12,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/4/0x7c17c8867d43c5d1F762a74cdD1509E20c8C7b02/sources/SmartInvoice.sol | client transfers locker funds upto certain milestone to provider | function release(uint256 _milestone) public nonReentrant {
require(!locked, "locked");
require(_msgSender() == client, "!client");
require(_milestone >= milestone, "milestone passed");
require(_milestone < amounts.length, "invalid milestone");
uint256 amount = 0;
for (uint256 j = milestone; j <= _milestone; j++) {
amount = amount.add(amounts[j]);
emit Release(j, amounts[j]);
}
uint256 balance = IERC20(token).balanceOf(address(this));
require(balance >= amount, "insufficient balance");
IERC20(token).safeTransfer(provider, amount);
released = released.add(amount);
milestone = _milestone.add(1);
}
| 8,519,352 | [
1,
2625,
29375,
28152,
284,
19156,
582,
21910,
8626,
28664,
358,
2893,
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,
225,
445,
3992,
12,
11890,
5034,
389,
81,
18270,
13,
1071,
1661,
426,
8230,
970,
288,
203,
565,
2583,
12,
5,
15091,
16,
315,
15091,
8863,
203,
565,
2583,
24899,
3576,
12021,
1435,
422,
1004,
16,
17528,
2625,
8863,
203,
565,
2583,
24899,
81,
18270,
1545,
28664,
16,
315,
81,
18270,
2275,
8863,
203,
565,
2583,
24899,
81,
18270,
411,
30980,
18,
2469,
16,
315,
5387,
28664,
8863,
203,
565,
2254,
5034,
3844,
273,
374,
31,
203,
565,
364,
261,
11890,
5034,
525,
273,
28664,
31,
525,
1648,
389,
81,
18270,
31,
525,
27245,
288,
203,
1377,
3844,
273,
3844,
18,
1289,
12,
8949,
87,
63,
78,
19226,
203,
1377,
3626,
10819,
12,
78,
16,
30980,
63,
78,
19226,
203,
565,
289,
203,
565,
2254,
5034,
11013,
273,
467,
654,
39,
3462,
12,
2316,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
565,
2583,
12,
12296,
1545,
3844,
16,
315,
2679,
11339,
11013,
8863,
203,
203,
565,
467,
654,
39,
3462,
12,
2316,
2934,
4626,
5912,
12,
6778,
16,
3844,
1769,
203,
565,
15976,
273,
15976,
18,
1289,
12,
8949,
1769,
203,
565,
28664,
273,
389,
81,
18270,
18,
1289,
12,
21,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.1;
/**
* @title Access Control List
*
* @notice Access control smart contract provides an API to check
* if specific operation is permitted globally and/or
* if particular user has a permission to execute it.
*
* @notice It deals with two main entities: features and roles.
*
* @notice Features are designed to be used to enable/disable specific
* functions (public functions) of the smart contract for everyone.
* @notice User roles are designed to restrict access to specific
* functions (restricted functions) of the smart contract to some users.
*
* @notice Terms "role", "permissions" and "set of permissions" have equal meaning
* in the documentation text and may be used interchangeably.
* @notice Terms "permission", "single permission" implies only one permission bit set.
*
* @dev This smart contract is designed to be inherited by other
* smart contracts which require access control management capabilities.
*
* @author Basil Gorin
*/
contract AccessControl {
/**
* @notice Access manager is responsible for assigning the roles to users,
* enabling/disabling global features of the smart contract
* @notice Access manager can add, remove and update user roles,
* remove and update global features
*
* @dev Role ROLE_ACCESS_MANAGER allows modifying user roles and global features
* @dev Role ROLE_ACCESS_MANAGER has single bit at position 255 enabled
*/
uint256 public constant ROLE_ACCESS_MANAGER = 0x8000000000000000000000000000000000000000000000000000000000000000;
/**
* @dev Bitmask representing all the possible permissions (super admin role)
* @dev Has all the bits are enabled (2^256 - 1 value)
*/
uint256 private constant FULL_PRIVILEGES_MASK = type(uint256).max; // before 0.8.0: uint256(-1) overflows to 0xFFFF...
/**
* @notice Privileged addresses with defined roles/permissions
* @notice In the context of ERC20/ERC721 tokens these can be permissions to
* allow minting or burning tokens, transferring on behalf and so on
*
* @dev Maps user address to the permissions bitmask (role), where each bit
* represents a permission
* @dev Bitmask 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
* represents all possible permissions
* @dev Zero address mapping represents global features of the smart contract
*/
mapping(address => uint256) public userRoles;
/**
* @dev Fired in updateRole() and updateFeatures()
*
* @param _by operator which called the function
* @param _to address which was granted/revoked permissions
* @param _requested permissions requested
* @param _actual permissions effectively set
*/
event RoleUpdated(address indexed _by, address indexed _to, uint256 _requested, uint256 _actual);
/**
* @notice Creates an access control instance,
* setting contract creator to have full privileges
*/
constructor() {
// contract creator has full privileges
userRoles[msg.sender] = FULL_PRIVILEGES_MASK;
}
/**
* @notice Retrieves globally set of features enabled
*
* @dev Auxiliary getter function to maintain compatibility with previous
* versions of the Access Control List smart contract, where
* features was a separate uint256 public field
*
* @return 256-bit bitmask of the features enabled
*/
function features() public view returns (uint256) {
// according to new design features are stored in zero address
// mapping of `userRoles` structure
return userRoles[address(0)];
}
/**
* @notice Updates set of the globally enabled features (`features`),
* taking into account sender's permissions
*
* @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
* @dev Function is left for backward compatibility with older versions
*
* @param _mask bitmask representing a set of features to enable/disable
*/
function updateFeatures(uint256 _mask) public {
// delegate call to `updateRole`
updateRole(address(0), _mask);
}
/**
* @notice Updates set of permissions (role) for a given user,
* taking into account sender's permissions.
*
* @dev Setting role to zero is equivalent to removing an all permissions
* @dev Setting role to `FULL_PRIVILEGES_MASK` is equivalent to
* copying senders' permissions (role) to the user
* @dev Requires transaction sender to have `ROLE_ACCESS_MANAGER` permission
*
* @param operator address of a user to alter permissions for or zero
* to alter global features of the smart contract
* @param role bitmask representing a set of permissions to
* enable/disable for a user specified
*/
function updateRole(address operator, uint256 role) public {
// caller must have a permission to update user roles
require(isSenderInRole(ROLE_ACCESS_MANAGER), "insufficient privileges (ROLE_ACCESS_MANAGER required)");
// evaluate the role and reassign it
userRoles[operator] = evaluateBy(msg.sender, userRoles[operator], role);
// fire an event
emit RoleUpdated(msg.sender, operator, role, userRoles[operator]);
}
/**
* @notice Determines the permission bitmask an operator can set on the
* target permission set
* @notice Used to calculate the permission bitmask to be set when requested
* in `updateRole` and `updateFeatures` functions
*
* @dev Calculated based on:
* 1) operator's own permission set read from userRoles[operator]
* 2) target permission set - what is already set on the target
* 3) desired permission set - what do we want set target to
*
* @dev Corner cases:
* 1) Operator is super admin and its permission set is `FULL_PRIVILEGES_MASK`:
* `desired` bitset is returned regardless of the `target` permission set value
* (what operator sets is what they get)
* 2) Operator with no permissions (zero bitset):
* `target` bitset is returned regardless of the `desired` value
* (operator has no authority and cannot modify anything)
*
* @dev Example:
* Consider an operator with the permissions bitmask 00001111
* is about to modify the target permission set 01010101
* Operator wants to set that permission set to 00110011
* Based on their role, an operator has the permissions
* to update only lowest 4 bits on the target, meaning that
* high 4 bits of the target set in this example is left
* unchanged and low 4 bits get changed as desired: 01010011
*
* @param operator address of the contract operator which is about to set the permissions
* @param target input set of permissions to operator is going to modify
* @param desired desired set of permissions operator would like to set
* @return resulting set of permissions given operator will set
*/
function evaluateBy(
address operator,
uint256 target,
uint256 desired
) public view returns (uint256) {
// read operator's permissions
uint256 p = userRoles[operator];
// taking into account operator's permissions,
// 1) enable the permissions desired on the `target`
target |= p & desired;
// 2) disable the permissions desired on the `target`
target &= FULL_PRIVILEGES_MASK ^ (p & (FULL_PRIVILEGES_MASK ^ desired));
// return calculated result
return target;
}
/**
* @notice Checks if requested set of features is enabled globally on the contract
*
* @param required set of features to check against
* @return true if all the features requested are enabled, false otherwise
*/
function isFeatureEnabled(uint256 required) public view returns (bool) {
// delegate call to `__hasRole`, passing `features` property
return __hasRole(features(), required);
}
/**
* @notice Checks if transaction sender `msg.sender` has all the permissions required
*
* @param required set of permissions (role) to check against
* @return true if all the permissions requested are enabled, false otherwise
*/
function isSenderInRole(uint256 required) public view returns (bool) {
// delegate call to `isOperatorInRole`, passing transaction sender
return isOperatorInRole(msg.sender, required);
}
/**
* @notice Checks if operator has all the permissions (role) required
*
* @param operator address of the user to check role for
* @param required set of permissions (role) to check
* @return true if all the permissions requested are enabled, false otherwise
*/
function isOperatorInRole(address operator, uint256 required) public view returns (bool) {
// delegate call to `__hasRole`, passing operator's permissions (role)
return __hasRole(userRoles[operator], required);
}
/**
* @dev Checks if role `actual` contains all the permissions required `required`
*
* @param actual existent role
* @param required required role
* @return true if actual has required role (all permissions), false otherwise
*/
function __hasRole(uint256 actual, uint256 required) internal pure returns (bool) {
// check the bitmask for the role required and return the result
return actual & required == required;
}
}
| * @notice Retrieves globally set of features enabled @dev Auxiliary getter function to maintain compatibility with previous versions of the Access Control List smart contract, where features was a separate uint256 public field @return 256-bit bitmask of the features enabled/ according to new design features are stored in zero address mapping of `userRoles` structure | function features() public view returns (uint256) {
return userRoles[address(0)];
}
| 1,070,905 | [
1,
6960,
25654,
444,
434,
4467,
3696,
225,
432,
2616,
20606,
7060,
445,
358,
17505,
8926,
598,
2416,
1377,
5244,
434,
326,
5016,
8888,
987,
13706,
6835,
16,
1625,
1377,
4467,
1703,
279,
9004,
2254,
5034,
1071,
652,
327,
8303,
17,
3682,
24941,
434,
326,
4467,
3696,
19,
4888,
358,
394,
8281,
4467,
854,
4041,
316,
3634,
1758,
2874,
434,
1375,
1355,
6898,
68,
3695,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
225,
445,
4467,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
729,
6898,
63,
2867,
12,
20,
13,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x66A85C93526f5a0BA33F29b43035b7fF864E739A/sources/project_/contracts/TokenOfAppreciation.sol | ✧・゚: *✧・゚:* 1. Property Variables ✧・゚: *✧・゚:* ✧・゚: *✧・゚:* 2. Constructor ✧・゚: *✧・゚:* | contract TokenOfAppreciation is ERC1155, ERC1155Burnable, Ownable {
string public constant name = "eCardDemo";
string public constant symbol = "ECD";
mapping (string => uint256) public tokenIds;
constructor(
tokenIds["cucumber"] = 1;
tokenIds["strawbeary"] = 2;
tokenIds["star"] = 3;
pragma solidity ^0.8.9;
}
| 1,917,111 | [
1,
163,
255,
105,
176,
126,
103,
176,
127,
258,
30,
225,
163,
255,
105,
176,
126,
103,
176,
127,
258,
30,
404,
18,
4276,
23536,
225,
163,
255,
105,
176,
126,
103,
176,
127,
258,
30,
225,
163,
255,
105,
176,
126,
103,
176,
127,
258,
30,
225,
225,
163,
255,
105,
176,
126,
103,
176,
127,
258,
30,
225,
163,
255,
105,
176,
126,
103,
176,
127,
258,
30,
576,
18,
11417,
225,
163,
255,
105,
176,
126,
103,
176,
127,
258,
30,
225,
163,
255,
105,
176,
126,
103,
176,
127,
258,
30,
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,
16351,
3155,
951,
1294,
4036,
7072,
353,
4232,
39,
2499,
2539,
16,
4232,
39,
2499,
2539,
38,
321,
429,
16,
14223,
6914,
288,
203,
203,
203,
565,
533,
1071,
5381,
508,
273,
315,
73,
6415,
27126,
14432,
203,
565,
533,
1071,
5381,
3273,
273,
315,
7228,
40,
14432,
203,
565,
2874,
261,
1080,
516,
2254,
5034,
13,
1071,
1147,
2673,
31,
203,
203,
203,
565,
3885,
12,
203,
3639,
1147,
2673,
9614,
71,
5286,
1226,
11929,
273,
404,
31,
203,
3639,
1147,
2673,
9614,
701,
2219,
2196,
814,
11929,
273,
576,
31,
203,
3639,
1147,
2673,
9614,
10983,
11929,
273,
890,
31,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
29,
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
]
|
./partial_match/1/0x91C986709Bb4fE0763edF8E2690EE9d5019Bea4a/sources/contracts/utils/Ownable.sol | @title Ownable Contract @author imToken Labs | abstract contract Ownable {
address public owner;
address public nominatedOwner;
event OwnerNominated(address indexed newOwner);
event OwnerChanged(address indexed oldOwner, address indexed newOwner);
pragma solidity ^0.7.6;
constructor(address _owner) {
require(_owner != address(0), "owner should not be 0");
owner = _owner;
}
modifier onlyOwner() {
require(msg.sender == owner, "not owner");
_;
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "not nominated");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
function renounceOwnership() external onlyOwner {
require(nominatedOwner == address(0), "pending nomination exists");
emit OwnerChanged(owner, address(0));
owner = address(0);
}
function nominateNewOwner(address newOwner) external onlyOwner {
nominatedOwner = newOwner;
emit OwnerNominated(newOwner);
}
}
| 2,657,048 | [
1,
5460,
429,
13456,
225,
709,
1345,
511,
5113,
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,
17801,
6835,
14223,
6914,
288,
203,
565,
1758,
1071,
3410,
31,
203,
565,
1758,
1071,
12457,
7458,
5541,
31,
203,
203,
565,
871,
16837,
26685,
7458,
12,
2867,
8808,
394,
5541,
1769,
203,
565,
871,
16837,
5033,
12,
2867,
8808,
1592,
5541,
16,
1758,
8808,
394,
5541,
1769,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
27,
18,
26,
31,
203,
565,
3885,
12,
2867,
389,
8443,
13,
288,
203,
3639,
2583,
24899,
8443,
480,
1758,
12,
20,
3631,
315,
8443,
1410,
486,
506,
374,
8863,
203,
3639,
3410,
273,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
16,
315,
902,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
2791,
5460,
12565,
1435,
3903,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
12457,
7458,
5541,
16,
315,
902,
12457,
7458,
8863,
203,
3639,
3626,
16837,
5033,
12,
8443,
16,
12457,
7458,
5541,
1769,
203,
203,
3639,
3410,
273,
12457,
7458,
5541,
31,
203,
3639,
12457,
7458,
5541,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
12306,
7458,
5541,
422,
1758,
12,
20,
3631,
315,
9561,
12457,
1735,
1704,
8863,
203,
3639,
3626,
16837,
5033,
12,
8443,
16,
1758,
12,
20,
10019,
203,
3639,
3410,
273,
1758,
12,
20,
1769,
203,
565,
289,
203,
203,
565,
445,
12457,
3322,
1908,
5541,
12,
2867,
394,
5541,
13,
2
]
|
./full_match/1/0xdE3C590b1A4442314a91277668D63Ab5EbbE7340/sources/contracts/KamiContract/Kami.sol | * @dev Mints Kami/* Source of randomness. Theoretical miner withhold manipulation possible but should be sufficient in a pragmatic sense/ | function mintNFT(uint256 numberOfNfts) public payable {
require(block.timestamp >= SALE_START_TIMESTAMP, "Sorry, you cannot buy Kamis at the moment");
require(totalSupply() < MAX_NFT_SUPPLY, "Sale has already ended");
require(numberOfNfts > 0, "Number of NFTs cannot be 0");
require(numberOfNfts <= 40, "You may not buy more than 40 NFTs at once");
require(totalSupply().add(numberOfNfts) <= MAX_NFT_SUPPLY, "Exceeds MAX_NFT_SUPPLY");
require(NFT_PRICE.mul(numberOfNfts) == msg.value, "Ether value sent is not correct");
for (uint i = 0; i < numberOfNfts; i++) {
uint mintIndex = totalSupply();
if (block.timestamp < REVEAL_TIMESTAMP) {
_mintedBeforeReveal[mintIndex] = true;
}
_mint(msg.sender, mintIndex);
}
if (startingSeedBlock == 0 && (totalSupply() == MAX_NFT_SUPPLY || block.timestamp >= REVEAL_TIMESTAMP)) {
startingSeedBlock = block.number;
}
}
| 9,684,169 | [
1,
49,
28142,
25188,
77,
19,
4998,
434,
2744,
4496,
18,
1021,
479,
88,
1706,
1131,
264,
598,
21056,
27029,
3323,
1496,
1410,
506,
18662,
316,
279,
846,
346,
26500,
12764,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
312,
474,
50,
4464,
12,
11890,
5034,
7922,
50,
1222,
87,
13,
1071,
8843,
429,
288,
203,
3639,
2583,
12,
2629,
18,
5508,
1545,
17127,
900,
67,
7570,
67,
17201,
16,
315,
28898,
16,
1846,
2780,
30143,
25188,
291,
622,
326,
10382,
8863,
203,
3639,
2583,
12,
4963,
3088,
1283,
1435,
411,
4552,
67,
50,
4464,
67,
13272,
23893,
16,
315,
30746,
711,
1818,
16926,
8863,
203,
3639,
2583,
12,
2696,
951,
50,
1222,
87,
405,
374,
16,
315,
1854,
434,
423,
4464,
87,
2780,
506,
374,
8863,
203,
3639,
2583,
12,
2696,
951,
50,
1222,
87,
1648,
8063,
16,
315,
6225,
2026,
486,
30143,
1898,
2353,
8063,
423,
4464,
87,
622,
3647,
8863,
203,
3639,
2583,
12,
4963,
3088,
1283,
7675,
1289,
12,
2696,
951,
50,
1222,
87,
13,
1648,
4552,
67,
50,
4464,
67,
13272,
23893,
16,
315,
424,
5288,
87,
4552,
67,
50,
4464,
67,
13272,
23893,
8863,
203,
3639,
2583,
12,
50,
4464,
67,
7698,
1441,
18,
16411,
12,
2696,
951,
50,
1222,
87,
13,
422,
1234,
18,
1132,
16,
315,
41,
1136,
460,
3271,
353,
486,
3434,
8863,
203,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
7922,
50,
1222,
87,
31,
277,
27245,
288,
203,
5411,
2254,
312,
474,
1016,
273,
2078,
3088,
1283,
5621,
203,
5411,
309,
261,
2629,
18,
5508,
411,
2438,
3412,
1013,
67,
17201,
13,
288,
203,
7734,
389,
81,
474,
329,
4649,
426,
24293,
63,
81,
474,
1016,
65,
273,
638,
31,
203,
5411,
289,
203,
5411,
389,
2
]
|
pragma solidity >=0.5.11;
//Represents the money being traded in this program
contract Money {
int amount; //Amount that this Money object holds
constructor(int amt) public {
amount = amt;
}
//Add additional Money
function mergeMoney(Money m) public {
amount = amount + m.getAmount();
}
//Returns the amount of this Money
function getAmount() public view returns (int) {
return amount;
}
// DANGER: for internal use only!
function addAmount(int amt) public {
amount += amt;
}
//Use some amount of this Money
function splitMoneyInto(int amt, Money otherMoney) public {
if (amt > amount) {
revert ("Can't split out more money than is available in a given Money object.");
} else {
amount = amount - amt;
otherMoney.addAmount(amt);
}
}
}
//Represents the bet prediction of a Bettor
contract BetPrediction {
string public predictedOutcome; //the Bettor's prediction of the winning outcome
int public betAmount; //the amount of money the Bettor put down on this BetPrediction
constructor(string memory predOut, int amount) public {
predictedOutcome = predOut;
betAmount = amount;
}
}
//Represents a person betting on a game
contract Bettor {
Money money; //Total Money the Bettor owns
constructor(Money m) public {
money = m;
}
//Take some Money out of the Bettor's total money
function withdrawMoney(int amount) public returns (Money) {
Money newMoney = new Money(0);
money.splitMoneyInto(amount, newMoney);
return newMoney;
}
//Adds Money to the Bettor's total money
function receiveMoney(Money m) public {
money.mergeMoney(m);
}
}
//Represents a single bet
contract Bet {
Bettor public bettor; //The Bettor making the bet
BetPrediction public prediction; //The BetPrediction for the winner
constructor(Bettor b, BetPrediction p) public {
bettor = b;
prediction = p;
}
}
//Represents a container of Bets
contract BetList {
Bet[] bets;
//Add a new Bet to the end of the list
function append(Bet newB) public {
bets.push(newB);
}
//remove a Bet with a given Bettor reference, and return that Bet
function popSpecific(Bettor bettor) public returns (Bet) {
for (uint i = 0; i < bets.length; i++) {
if (bets[i].bettor() == bettor) {
Bet result = bets[i];
bets[i] = bets[bets.length - 1];
delete bets[bets.length - 1];
bets.length--;
return result;
}
}
revert("No matching bets in list");
}
//returns true if a Bet has been placed by a Bettor
function contains(Bettor bettor) public view returns (bool) {
for (uint i = 0; i < bets.length; i++) {
if (bets[i].bettor() == bettor) {
return true;
}
}
}
}
//Represents a generic game
contract Game {
enum State { BeforePlay, Playing, FinishedPlaying}
State state;
constructor() public {
state = State.BeforePlay;
}
//Start the game
function startPlaying() public {
require(state == State.BeforePlay, "Wrong initial state.");
state = State.Playing;
}
//Finish the game
function finishPlaying() public {
require(state == State.Playing, "Wrong initial state.");
state = State.FinishedPlaying;
}
//Returns the outcome of the game
function calculateOutcome() public view returns (string memory) {
require(state == State.FinishedPlaying, "Wrong initial state.");
//...
return ""; //Always returns empty string for now
}
} | The Bettor making the bet
| Bettor public bettor; | 12,673,732 | [
1,
1986,
605,
278,
13039,
10480,
326,
2701,
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,
605,
278,
13039,
1071,
2701,
13039,
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
]
|
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {PercentageMath} from '../protocol/libraries/math/PercentageMath.sol';
import {SafeMath} from '../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol';
import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol';
import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol';
import {IERC20WithPermit} from '../interfaces/IERC20WithPermit.sol';
import {FlashLoanReceiverBase} from '../flashloan/base/FlashLoanReceiverBase.sol';
import {IBaseUniswapAdapter} from './interfaces/IBaseUniswapAdapter.sol';
/**
* @title BaseUniswapAdapter
* @notice Implements the logic for performing assets swaps in Uniswap V2
* @author Aave
**/
abstract contract BaseUniswapAdapter is FlashLoanReceiverBase, IBaseUniswapAdapter, Ownable {
using SafeMath for uint256;
using PercentageMath for uint256;
using SafeERC20 for IERC20;
// Max slippage percent allowed
uint256 public constant override MAX_SLIPPAGE_PERCENT = 3000; // 30%
// FLash Loan fee set in lending pool
uint256 public constant override FLASHLOAN_PREMIUM_TOTAL = 9;
// USD oracle asset address
address public constant override USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96;
address public immutable override WETH_ADDRESS;
IPriceOracleGetter public immutable override ORACLE;
IUniswapV2Router02 public immutable override UNISWAP_ROUTER;
constructor(
ILendingPoolAddressesProvider addressesProvider,
IUniswapV2Router02 uniswapRouter,
address wethAddress
) public FlashLoanReceiverBase(addressesProvider) {
ORACLE = IPriceOracleGetter(addressesProvider.getPriceOracle());
UNISWAP_ROUTER = uniswapRouter;
WETH_ADDRESS = wethAddress;
}
/**
* @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices
* @param amountIn Amount of reserveIn
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @return uint256 Amount out of the reserveOut
* @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals)
* @return uint256 In amount of reserveIn value denominated in USD (8 decimals)
* @return uint256 Out amount of reserveOut value denominated in USD (8 decimals)
*/
function getAmountsOut(
uint256 amountIn,
address reserveIn,
address reserveOut
)
external
view
override
returns (
uint256,
uint256,
uint256,
uint256,
address[] memory
)
{
AmountCalc memory results = _getAmountsOutData(reserveIn, reserveOut, amountIn);
return (
results.calculatedAmount,
results.relativePrice,
results.amountInUsd,
results.amountOutUsd,
results.path
);
}
/**
* @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices
* @param amountOut Amount of reserveOut
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @return uint256 Amount in of the reserveIn
* @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals)
* @return uint256 In amount of reserveIn value denominated in USD (8 decimals)
* @return uint256 Out amount of reserveOut value denominated in USD (8 decimals)
*/
function getAmountsIn(
uint256 amountOut,
address reserveIn,
address reserveOut
)
external
view
override
returns (
uint256,
uint256,
uint256,
uint256,
address[] memory
)
{
AmountCalc memory results = _getAmountsInData(reserveIn, reserveOut, amountOut);
return (
results.calculatedAmount,
results.relativePrice,
results.amountInUsd,
results.amountOutUsd,
results.path
);
}
/**
* @dev Swaps an exact `amountToSwap` of an asset to another
* @param assetToSwapFrom Origin asset
* @param assetToSwapTo Destination asset
* @param amountToSwap Exact amount of `assetToSwapFrom` to be swapped
* @param minAmountOut the min amount of `assetToSwapTo` to be received from the swap
* @return the amount received from the swap
*/
function _swapExactTokensForTokens(
address assetToSwapFrom,
address assetToSwapTo,
uint256 amountToSwap,
uint256 minAmountOut,
bool useEthPath
) internal returns (uint256) {
uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom);
uint256 toAssetDecimals = _getDecimals(assetToSwapTo);
uint256 fromAssetPrice = _getPrice(assetToSwapFrom);
uint256 toAssetPrice = _getPrice(assetToSwapTo);
uint256 expectedMinAmountOut =
amountToSwap
.mul(fromAssetPrice.mul(10**toAssetDecimals))
.div(toAssetPrice.mul(10**fromAssetDecimals))
.percentMul(PercentageMath.PERCENTAGE_FACTOR.sub(MAX_SLIPPAGE_PERCENT));
require(expectedMinAmountOut < minAmountOut, 'minAmountOut exceed max slippage');
// Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0);
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), amountToSwap);
address[] memory path;
if (useEthPath) {
path = new address[](3);
path[0] = assetToSwapFrom;
path[1] = WETH_ADDRESS;
path[2] = assetToSwapTo;
} else {
path = new address[](2);
path[0] = assetToSwapFrom;
path[1] = assetToSwapTo;
}
uint256[] memory amounts =
UNISWAP_ROUTER.swapExactTokensForTokens(
amountToSwap,
minAmountOut,
path,
address(this),
block.timestamp
);
emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]);
return amounts[amounts.length - 1];
}
/**
* @dev Receive an exact amount `amountToReceive` of `assetToSwapTo` tokens for as few `assetToSwapFrom` tokens as
* possible.
* @param assetToSwapFrom Origin asset
* @param assetToSwapTo Destination asset
* @param maxAmountToSwap Max amount of `assetToSwapFrom` allowed to be swapped
* @param amountToReceive Exact amount of `assetToSwapTo` to receive
* @return the amount swapped
*/
function _swapTokensForExactTokens(
address assetToSwapFrom,
address assetToSwapTo,
uint256 maxAmountToSwap,
uint256 amountToReceive,
bool useEthPath
) internal returns (uint256) {
uint256 fromAssetDecimals = _getDecimals(assetToSwapFrom);
uint256 toAssetDecimals = _getDecimals(assetToSwapTo);
uint256 fromAssetPrice = _getPrice(assetToSwapFrom);
uint256 toAssetPrice = _getPrice(assetToSwapTo);
uint256 expectedMaxAmountToSwap =
amountToReceive
.mul(toAssetPrice.mul(10**fromAssetDecimals))
.div(fromAssetPrice.mul(10**toAssetDecimals))
.percentMul(PercentageMath.PERCENTAGE_FACTOR.add(MAX_SLIPPAGE_PERCENT));
require(maxAmountToSwap < expectedMaxAmountToSwap, 'maxAmountToSwap exceed max slippage');
// Approves the transfer for the swap. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), 0);
IERC20(assetToSwapFrom).safeApprove(address(UNISWAP_ROUTER), maxAmountToSwap);
address[] memory path;
if (useEthPath) {
path = new address[](3);
path[0] = assetToSwapFrom;
path[1] = WETH_ADDRESS;
path[2] = assetToSwapTo;
} else {
path = new address[](2);
path[0] = assetToSwapFrom;
path[1] = assetToSwapTo;
}
uint256[] memory amounts =
UNISWAP_ROUTER.swapTokensForExactTokens(
amountToReceive,
maxAmountToSwap,
path,
address(this),
block.timestamp
);
emit Swapped(assetToSwapFrom, assetToSwapTo, amounts[0], amounts[amounts.length - 1]);
return amounts[0];
}
/**
* @dev Get the price of the asset from the oracle denominated in eth
* @param asset address
* @return eth price for the asset
*/
function _getPrice(address asset) internal view returns (uint256) {
return ORACLE.getAssetPrice(asset);
}
/**
* @dev Get the decimals of an asset
* @return number of decimals of the asset
*/
function _getDecimals(address asset) internal view returns (uint256) {
return IERC20Detailed(asset).decimals();
}
/**
* @dev Get the aToken associated to the asset
* @return address of the aToken
*/
function _getReserveData(address asset) internal view returns (DataTypes.ReserveData memory) {
return LENDING_POOL.getReserveData(asset);
}
/**
* @dev Pull the ATokens from the user
* @param reserve address of the asset
* @param reserveAToken address of the aToken of the reserve
* @param user address
* @param amount of tokens to be transferred to the contract
* @param permitSignature struct containing the permit signature
*/
function _pullAToken(
address reserve,
address reserveAToken,
address user,
uint256 amount,
PermitSignature memory permitSignature
) internal {
if (_usePermit(permitSignature)) {
IERC20WithPermit(reserveAToken).permit(
user,
address(this),
permitSignature.amount,
permitSignature.deadline,
permitSignature.v,
permitSignature.r,
permitSignature.s
);
}
// transfer from user to adapter
IERC20(reserveAToken).safeTransferFrom(user, address(this), amount);
// withdraw reserve
LENDING_POOL.withdraw(reserve, amount, address(this));
}
/**
* @dev Tells if the permit method should be called by inspecting if there is a valid signature.
* If signature params are set to 0, then permit won't be called.
* @param signature struct containing the permit signature
* @return whether or not permit should be called
*/
function _usePermit(PermitSignature memory signature) internal pure returns (bool) {
return
!(uint256(signature.deadline) == uint256(signature.v) && uint256(signature.deadline) == 0);
}
/**
* @dev Calculates the value denominated in USD
* @param reserve Address of the reserve
* @param amount Amount of the reserve
* @param decimals Decimals of the reserve
* @return whether or not permit should be called
*/
function _calcUsdValue(
address reserve,
uint256 amount,
uint256 decimals
) internal view returns (uint256) {
uint256 ethUsdPrice = _getPrice(USD_ADDRESS);
uint256 reservePrice = _getPrice(reserve);
return amount.mul(reservePrice).div(10**decimals).mul(ethUsdPrice).div(10**18);
}
/**
* @dev Given an input asset amount, returns the maximum output amount of the other asset
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @param amountIn Amount of reserveIn
* @return Struct containing the following information:
* uint256 Amount out of the reserveOut
* uint256 The price of out amount denominated in the reserveIn currency (18 decimals)
* uint256 In amount of reserveIn value denominated in USD (8 decimals)
* uint256 Out amount of reserveOut value denominated in USD (8 decimals)
*/
function _getAmountsOutData(
address reserveIn,
address reserveOut,
uint256 amountIn
) internal view returns (AmountCalc memory) {
// Subtract flash loan fee
uint256 finalAmountIn = amountIn.sub(amountIn.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000));
if (reserveIn == reserveOut) {
uint256 reserveDecimals = _getDecimals(reserveIn);
address[] memory path = new address[](1);
path[0] = reserveIn;
return
AmountCalc(
finalAmountIn,
finalAmountIn.mul(10**18).div(amountIn),
_calcUsdValue(reserveIn, amountIn, reserveDecimals),
_calcUsdValue(reserveIn, finalAmountIn, reserveDecimals),
path
);
}
address[] memory simplePath = new address[](2);
simplePath[0] = reserveIn;
simplePath[1] = reserveOut;
uint256[] memory amountsWithoutWeth;
uint256[] memory amountsWithWeth;
address[] memory pathWithWeth = new address[](3);
if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) {
pathWithWeth[0] = reserveIn;
pathWithWeth[1] = WETH_ADDRESS;
pathWithWeth[2] = reserveOut;
try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, pathWithWeth) returns (
uint256[] memory resultsWithWeth
) {
amountsWithWeth = resultsWithWeth;
} catch {
amountsWithWeth = new uint256[](3);
}
} else {
amountsWithWeth = new uint256[](3);
}
uint256 bestAmountOut;
try UNISWAP_ROUTER.getAmountsOut(finalAmountIn, simplePath) returns (
uint256[] memory resultAmounts
) {
amountsWithoutWeth = resultAmounts;
bestAmountOut = (amountsWithWeth[2] > amountsWithoutWeth[1])
? amountsWithWeth[2]
: amountsWithoutWeth[1];
} catch {
amountsWithoutWeth = new uint256[](2);
bestAmountOut = amountsWithWeth[2];
}
uint256 reserveInDecimals = _getDecimals(reserveIn);
uint256 reserveOutDecimals = _getDecimals(reserveOut);
uint256 outPerInPrice =
finalAmountIn.mul(10**18).mul(10**reserveOutDecimals).div(
bestAmountOut.mul(10**reserveInDecimals)
);
return
AmountCalc(
bestAmountOut,
outPerInPrice,
_calcUsdValue(reserveIn, amountIn, reserveInDecimals),
_calcUsdValue(reserveOut, bestAmountOut, reserveOutDecimals),
(bestAmountOut == 0) ? new address[](2) : (bestAmountOut == amountsWithoutWeth[1])
? simplePath
: pathWithWeth
);
}
/**
* @dev Returns the minimum input asset amount required to buy the given output asset amount
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @param amountOut Amount of reserveOut
* @return Struct containing the following information:
* uint256 Amount in of the reserveIn
* uint256 The price of in amount denominated in the reserveOut currency (18 decimals)
* uint256 In amount of reserveIn value denominated in USD (8 decimals)
* uint256 Out amount of reserveOut value denominated in USD (8 decimals)
*/
function _getAmountsInData(
address reserveIn,
address reserveOut,
uint256 amountOut
) internal view returns (AmountCalc memory) {
if (reserveIn == reserveOut) {
// Add flash loan fee
uint256 amountIn = amountOut.add(amountOut.mul(FLASHLOAN_PREMIUM_TOTAL).div(10000));
uint256 reserveDecimals = _getDecimals(reserveIn);
address[] memory path = new address[](1);
path[0] = reserveIn;
return
AmountCalc(
amountIn,
amountOut.mul(10**18).div(amountIn),
_calcUsdValue(reserveIn, amountIn, reserveDecimals),
_calcUsdValue(reserveIn, amountOut, reserveDecimals),
path
);
}
(uint256[] memory amounts, address[] memory path) =
_getAmountsInAndPath(reserveIn, reserveOut, amountOut);
// Add flash loan fee
uint256 finalAmountIn = amounts[0].add(amounts[0].mul(FLASHLOAN_PREMIUM_TOTAL).div(10000));
uint256 reserveInDecimals = _getDecimals(reserveIn);
uint256 reserveOutDecimals = _getDecimals(reserveOut);
uint256 inPerOutPrice =
amountOut.mul(10**18).mul(10**reserveInDecimals).div(
finalAmountIn.mul(10**reserveOutDecimals)
);
return
AmountCalc(
finalAmountIn,
inPerOutPrice,
_calcUsdValue(reserveIn, finalAmountIn, reserveInDecimals),
_calcUsdValue(reserveOut, amountOut, reserveOutDecimals),
path
);
}
/**
* @dev Calculates the input asset amount required to buy the given output asset amount
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @param amountOut Amount of reserveOut
* @return uint256[] amounts Array containing the amountIn and amountOut for a swap
*/
function _getAmountsInAndPath(
address reserveIn,
address reserveOut,
uint256 amountOut
) internal view returns (uint256[] memory, address[] memory) {
address[] memory simplePath = new address[](2);
simplePath[0] = reserveIn;
simplePath[1] = reserveOut;
uint256[] memory amountsWithoutWeth;
uint256[] memory amountsWithWeth;
address[] memory pathWithWeth = new address[](3);
if (reserveIn != WETH_ADDRESS && reserveOut != WETH_ADDRESS) {
pathWithWeth[0] = reserveIn;
pathWithWeth[1] = WETH_ADDRESS;
pathWithWeth[2] = reserveOut;
try UNISWAP_ROUTER.getAmountsIn(amountOut, pathWithWeth) returns (
uint256[] memory resultsWithWeth
) {
amountsWithWeth = resultsWithWeth;
} catch {
amountsWithWeth = new uint256[](3);
}
} else {
amountsWithWeth = new uint256[](3);
}
try UNISWAP_ROUTER.getAmountsIn(amountOut, simplePath) returns (
uint256[] memory resultAmounts
) {
amountsWithoutWeth = resultAmounts;
return
(amountsWithWeth[0] < amountsWithoutWeth[0] && amountsWithWeth[0] != 0)
? (amountsWithWeth, pathWithWeth)
: (amountsWithoutWeth, simplePath);
} catch {
return (amountsWithWeth, pathWithWeth);
}
}
/**
* @dev Calculates the input asset amount required to buy the given output asset amount
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @param amountOut Amount of reserveOut
* @return uint256[] amounts Array containing the amountIn and amountOut for a swap
*/
function _getAmountsIn(
address reserveIn,
address reserveOut,
uint256 amountOut,
bool useEthPath
) internal view returns (uint256[] memory) {
address[] memory path;
if (useEthPath) {
path = new address[](3);
path[0] = reserveIn;
path[1] = WETH_ADDRESS;
path[2] = reserveOut;
} else {
path = new address[](2);
path[0] = reserveIn;
path[1] = reserveOut;
}
return UNISWAP_ROUTER.getAmountsIn(amountOut, path);
}
/**
* @dev Emergency rescue for token stucked on this contract, as failsafe mechanism
* - Funds should never remain in this contract more time than during transactions
* - Only callable by the owner
**/
function rescueTokens(IERC20 token) external onlyOwner {
token.transfer(owner(), token.balanceOf(address(this)));
}
}
// 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;
/**
* @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;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from './IERC20.sol';
interface IERC20Detailed is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import {IERC20} from './IERC20.sol';
import {SafeMath} from './SafeMath.sol';
import {Address} from './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));
}
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 callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), 'SafeERC20: call to non-contract');
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, 'SafeERC20: low-level call failed');
if (returndata.length > 0) {
// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), 'SafeERC20: ERC20 operation did not succeed');
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import './Context.sol';
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), 'Ownable: caller is not the owner');
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), 'Ownable: new owner is the zero address');
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: 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;
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IUniswapV2Router02 {
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title IPriceOracleGetter interface
* @notice Interface for the Aave price oracle.
**/
interface IPriceOracleGetter {
/**
* @dev returns the asset price in ETH
* @param asset the address of the asset
* @return the ETH price of the asset
**/
function getAssetPrice(address asset) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
interface IERC20WithPermit is IERC20 {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {IFlashLoanReceiver} from '../interfaces/IFlashLoanReceiver.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
abstract contract FlashLoanReceiverBase is IFlashLoanReceiver {
using SafeERC20 for IERC20;
using SafeMath for uint256;
ILendingPoolAddressesProvider public immutable override ADDRESSES_PROVIDER;
ILendingPool public immutable override LENDING_POOL;
constructor(ILendingPoolAddressesProvider provider) public {
ADDRESSES_PROVIDER = provider;
LENDING_POOL = ILendingPool(provider.getLendingPool());
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol';
import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol';
interface IBaseUniswapAdapter {
event Swapped(address fromAsset, address toAsset, uint256 fromAmount, uint256 receivedAmount);
struct PermitSignature {
uint256 amount;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
struct AmountCalc {
uint256 calculatedAmount;
uint256 relativePrice;
uint256 amountInUsd;
uint256 amountOutUsd;
address[] path;
}
function WETH_ADDRESS() external returns (address);
function MAX_SLIPPAGE_PERCENT() external returns (uint256);
function FLASHLOAN_PREMIUM_TOTAL() external returns (uint256);
function USD_ADDRESS() external returns (address);
function ORACLE() external returns (IPriceOracleGetter);
function UNISWAP_ROUTER() external returns (IUniswapV2Router02);
/**
* @dev Given an input asset amount, returns the maximum output amount of the other asset and the prices
* @param amountIn Amount of reserveIn
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @return uint256 Amount out of the reserveOut
* @return uint256 The price of out amount denominated in the reserveIn currency (18 decimals)
* @return uint256 In amount of reserveIn value denominated in USD (8 decimals)
* @return uint256 Out amount of reserveOut value denominated in USD (8 decimals)
* @return address[] The exchange path
*/
function getAmountsOut(
uint256 amountIn,
address reserveIn,
address reserveOut
)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
address[] memory
);
/**
* @dev Returns the minimum input asset amount required to buy the given output asset amount and the prices
* @param amountOut Amount of reserveOut
* @param reserveIn Address of the asset to be swap from
* @param reserveOut Address of the asset to be swap to
* @return uint256 Amount in of the reserveIn
* @return uint256 The price of in amount denominated in the reserveOut currency (18 decimals)
* @return uint256 In amount of reserveIn value denominated in USD (8 decimals)
* @return uint256 Out amount of reserveOut value denominated in USD (8 decimals)
* @return address[] The exchange path
*/
function getAmountsIn(
uint256 amountOut,
address reserveIn,
address reserveOut
)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
address[] memory
);
}
// 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;
/**
* @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');
}
}
// SPDX-License-Identifier: MIT
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;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
/**
* @title IFlashLoanReceiver interface
* @notice Interface for the Aave fee IFlashLoanReceiver.
* @author Aave
* @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract
**/
interface IFlashLoanReceiver {
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external returns (bool);
function ADDRESSES_PROVIDER() external view returns (ILendingPoolAddressesProvider);
function LENDING_POOL() external view returns (ILendingPool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {ILendingPoolAddressesProvider} from './ILendingPoolAddressesProvider.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(address indexed reserve, address indexed user);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external returns (uint256);
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress)
external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider() external view returns (ILendingPoolAddressesProvider);
function setPause(bool val) external;
function paused() external view returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
/**
* @title UniswapRepayAdapter
* @notice Uniswap V2 Adapter to perform a repay of a debt with collateral.
* @author Aave
**/
contract UniswapRepayAdapter is BaseUniswapAdapter {
struct RepayParams {
address collateralAsset;
uint256 collateralAmount;
uint256 rateMode;
PermitSignature permitSignature;
bool useEthPath;
}
constructor(
ILendingPoolAddressesProvider addressesProvider,
IUniswapV2Router02 uniswapRouter,
address wethAddress
) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {}
/**
* @dev Uses the received funds from the flash loan to repay a debt on the protocol on behalf of the user. Then pulls
* the collateral from the user and swaps it to the debt asset to repay the flash loan.
* The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset, swap it
* and repay the flash loan.
* Supports only one asset on the flash loan.
* @param assets Address of debt asset
* @param amounts Amount of the debt to be repaid
* @param premiums Fee of the flash loan
* @param initiator Address of the user
* @param params Additional variadic field to include extra params. Expected parameters:
* address collateralAsset Address of the reserve to be swapped
* uint256 collateralAmount Amount of reserve to be swapped
* uint256 rateMode Rate modes of the debt to be repaid
* uint256 permitAmount Amount for the permit signature
* uint256 deadline Deadline for the permit signature
* uint8 v V param for the permit signature
* bytes32 r R param for the permit signature
* bytes32 s S param for the permit signature
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL');
RepayParams memory decodedParams = _decodeParams(params);
_swapAndRepay(
decodedParams.collateralAsset,
assets[0],
amounts[0],
decodedParams.collateralAmount,
decodedParams.rateMode,
initiator,
premiums[0],
decodedParams.permitSignature,
decodedParams.useEthPath
);
return true;
}
/**
* @dev Swaps the user collateral for the debt asset and then repay the debt on the protocol on behalf of the user
* without using flash loans. This method can be used when the temporary transfer of the collateral asset to this
* contract does not affect the user position.
* The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset
* @param collateralAsset Address of asset to be swapped
* @param debtAsset Address of debt asset
* @param collateralAmount Amount of the collateral to be swapped
* @param debtRepayAmount Amount of the debt to be repaid
* @param debtRateMode Rate mode of the debt to be repaid
* @param permitSignature struct containing the permit signature
* @param useEthPath struct containing the permit signature
*/
function swapAndRepay(
address collateralAsset,
address debtAsset,
uint256 collateralAmount,
uint256 debtRepayAmount,
uint256 debtRateMode,
PermitSignature calldata permitSignature,
bool useEthPath
) external {
DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset);
DataTypes.ReserveData memory debtReserveData = _getReserveData(debtAsset);
address debtToken =
DataTypes.InterestRateMode(debtRateMode) == DataTypes.InterestRateMode.STABLE
? debtReserveData.stableDebtTokenAddress
: debtReserveData.variableDebtTokenAddress;
uint256 currentDebt = IERC20(debtToken).balanceOf(msg.sender);
uint256 amountToRepay = debtRepayAmount <= currentDebt ? debtRepayAmount : currentDebt;
if (collateralAsset != debtAsset) {
uint256 maxCollateralToSwap = collateralAmount;
if (amountToRepay < debtRepayAmount) {
maxCollateralToSwap = maxCollateralToSwap.mul(amountToRepay).div(debtRepayAmount);
}
// Get exact collateral needed for the swap to avoid leftovers
uint256[] memory amounts =
_getAmountsIn(collateralAsset, debtAsset, amountToRepay, useEthPath);
require(amounts[0] <= maxCollateralToSwap, 'slippage too high');
// Pull aTokens from user
_pullAToken(
collateralAsset,
collateralReserveData.aTokenAddress,
msg.sender,
amounts[0],
permitSignature
);
// Swap collateral for debt asset
_swapTokensForExactTokens(collateralAsset, debtAsset, amounts[0], amountToRepay, useEthPath);
} else {
// Pull aTokens from user
_pullAToken(
collateralAsset,
collateralReserveData.aTokenAddress,
msg.sender,
amountToRepay,
permitSignature
);
}
// Repay debt. Approves 0 first to comply with tokens that implement the anti frontrunning approval fix
IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0);
IERC20(debtAsset).safeApprove(address(LENDING_POOL), amountToRepay);
LENDING_POOL.repay(debtAsset, amountToRepay, debtRateMode, msg.sender);
}
/**
* @dev Perform the repay of the debt, pulls the initiator collateral and swaps to repay the flash loan
*
* @param collateralAsset Address of token to be swapped
* @param debtAsset Address of debt token to be received from the swap
* @param amount Amount of the debt to be repaid
* @param collateralAmount Amount of the reserve to be swapped
* @param rateMode Rate mode of the debt to be repaid
* @param initiator Address of the user
* @param premium Fee of the flash loan
* @param permitSignature struct containing the permit signature
*/
function _swapAndRepay(
address collateralAsset,
address debtAsset,
uint256 amount,
uint256 collateralAmount,
uint256 rateMode,
address initiator,
uint256 premium,
PermitSignature memory permitSignature,
bool useEthPath
) internal {
DataTypes.ReserveData memory collateralReserveData = _getReserveData(collateralAsset);
// Repay debt. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0);
IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount);
uint256 repaidAmount = IERC20(debtAsset).balanceOf(address(this));
LENDING_POOL.repay(debtAsset, amount, rateMode, initiator);
repaidAmount = repaidAmount.sub(IERC20(debtAsset).balanceOf(address(this)));
if (collateralAsset != debtAsset) {
uint256 maxCollateralToSwap = collateralAmount;
if (repaidAmount < amount) {
maxCollateralToSwap = maxCollateralToSwap.mul(repaidAmount).div(amount);
}
uint256 neededForFlashLoanDebt = repaidAmount.add(premium);
uint256[] memory amounts =
_getAmountsIn(collateralAsset, debtAsset, neededForFlashLoanDebt, useEthPath);
require(amounts[0] <= maxCollateralToSwap, 'slippage too high');
// Pull aTokens from user
_pullAToken(
collateralAsset,
collateralReserveData.aTokenAddress,
initiator,
amounts[0],
permitSignature
);
// Swap collateral asset to the debt asset
_swapTokensForExactTokens(
collateralAsset,
debtAsset,
amounts[0],
neededForFlashLoanDebt,
useEthPath
);
} else {
// Pull aTokens from user
_pullAToken(
collateralAsset,
collateralReserveData.aTokenAddress,
initiator,
repaidAmount.add(premium),
permitSignature
);
}
// Repay flashloan. Approves for 0 first to comply with tokens that implement the anti frontrunning approval fix.
IERC20(debtAsset).safeApprove(address(LENDING_POOL), 0);
IERC20(debtAsset).safeApprove(address(LENDING_POOL), amount.add(premium));
}
/**
* @dev Decodes debt information encoded in the flash loan params
* @param params Additional variadic field to include extra params. Expected parameters:
* address collateralAsset Address of the reserve to be swapped
* uint256 collateralAmount Amount of reserve to be swapped
* uint256 rateMode Rate modes of the debt to be repaid
* uint256 permitAmount Amount for the permit signature
* uint256 deadline Deadline for the permit signature
* uint8 v V param for the permit signature
* bytes32 r R param for the permit signature
* bytes32 s S param for the permit signature
* bool useEthPath use WETH path route
* @return RepayParams struct containing decoded params
*/
function _decodeParams(bytes memory params) internal pure returns (RepayParams memory) {
(
address collateralAsset,
uint256 collateralAmount,
uint256 rateMode,
uint256 permitAmount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s,
bool useEthPath
) =
abi.decode(
params,
(address, uint256, uint256, uint256, uint256, uint8, bytes32, bytes32, bool)
);
return
RepayParams(
collateralAsset,
collateralAmount,
rateMode,
PermitSignature(permitAmount, deadline, v, r, s),
useEthPath
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {SafeMath} from '../../dependencies/openzeppelin/contracts//SafeMath.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts//IERC20.sol';
import {IAToken} from '../../interfaces/IAToken.sol';
import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol';
import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol';
import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol';
import {ILendingPoolCollateralManager} from '../../interfaces/ILendingPoolCollateralManager.sol';
import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol';
import {GenericLogic} from '../libraries/logic/GenericLogic.sol';
import {Helpers} from '../libraries/helpers/Helpers.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {PercentageMath} from '../libraries/math/PercentageMath.sol';
import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol';
import {DataTypes} from '../libraries/types/DataTypes.sol';
import {LendingPoolStorage} from './LendingPoolStorage.sol';
/**
* @title LendingPoolCollateralManager contract
* @author Aave
* @dev Implements actions involving management of collateral in the protocol, the main one being the liquidations
* IMPORTANT This contract will run always via DELEGATECALL, through the LendingPool, so the chain of inheritance
* is the same as the LendingPool, to have compatible storage layouts
**/
contract LendingPoolCollateralManager is
ILendingPoolCollateralManager,
VersionedInitializable,
LendingPoolStorage
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
using WadRayMath for uint256;
using PercentageMath for uint256;
uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000;
struct LiquidationCallLocalVars {
uint256 userCollateralBalance;
uint256 userStableDebt;
uint256 userVariableDebt;
uint256 maxLiquidatableDebt;
uint256 actualDebtToLiquidate;
uint256 liquidationRatio;
uint256 maxAmountCollateralToLiquidate;
uint256 userStableRate;
uint256 maxCollateralToLiquidate;
uint256 debtAmountNeeded;
uint256 healthFactor;
uint256 liquidatorPreviousATokenBalance;
IAToken collateralAtoken;
bool isCollateralEnabled;
DataTypes.InterestRateMode borrowRateMode;
uint256 errorCode;
string errorMsg;
}
/**
* @dev As thIS contract extends the VersionedInitializable contract to match the state
* of the LendingPool contract, the getRevision() function is needed, but the value is not
* important, as the initialize() function will never be called here
*/
function getRevision() internal pure override returns (uint256) {
return 0;
}
/**
* @dev Function to liquidate a position if its Health Factor drops below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external override returns (uint256, string memory) {
DataTypes.ReserveData storage collateralReserve = _reserves[collateralAsset];
DataTypes.ReserveData storage debtReserve = _reserves[debtAsset];
DataTypes.UserConfigurationMap storage userConfig = _usersConfig[user];
LiquidationCallLocalVars memory vars;
(, , , , vars.healthFactor) = GenericLogic.calculateUserAccountData(
user,
_reserves,
userConfig,
_reservesList,
_reservesCount,
_addressesProvider.getPriceOracle()
);
(vars.userStableDebt, vars.userVariableDebt) = Helpers.getUserCurrentDebt(user, debtReserve);
(vars.errorCode, vars.errorMsg) = ValidationLogic.validateLiquidationCall(
collateralReserve,
debtReserve,
userConfig,
vars.healthFactor,
vars.userStableDebt,
vars.userVariableDebt
);
if (Errors.CollateralManagerErrors(vars.errorCode) != Errors.CollateralManagerErrors.NO_ERROR) {
return (vars.errorCode, vars.errorMsg);
}
vars.collateralAtoken = IAToken(collateralReserve.aTokenAddress);
vars.userCollateralBalance = vars.collateralAtoken.balanceOf(user);
vars.maxLiquidatableDebt = vars.userStableDebt.add(vars.userVariableDebt).percentMul(
LIQUIDATION_CLOSE_FACTOR_PERCENT
);
vars.actualDebtToLiquidate = debtToCover > vars.maxLiquidatableDebt
? vars.maxLiquidatableDebt
: debtToCover;
(
vars.maxCollateralToLiquidate,
vars.debtAmountNeeded
) = _calculateAvailableCollateralToLiquidate(
collateralReserve,
debtReserve,
collateralAsset,
debtAsset,
vars.actualDebtToLiquidate,
vars.userCollateralBalance
);
// If debtAmountNeeded < actualDebtToLiquidate, there isn't enough
// collateral to cover the actual amount that is being liquidated, hence we liquidate
// a smaller amount
if (vars.debtAmountNeeded < vars.actualDebtToLiquidate) {
vars.actualDebtToLiquidate = vars.debtAmountNeeded;
}
// If the liquidator reclaims the underlying asset, we make sure there is enough available liquidity in the
// collateral reserve
if (!receiveAToken) {
uint256 currentAvailableCollateral =
IERC20(collateralAsset).balanceOf(address(vars.collateralAtoken));
if (currentAvailableCollateral < vars.maxCollateralToLiquidate) {
return (
uint256(Errors.CollateralManagerErrors.NOT_ENOUGH_LIQUIDITY),
Errors.LPCM_NOT_ENOUGH_LIQUIDITY_TO_LIQUIDATE
);
}
}
debtReserve.updateState();
if (vars.userVariableDebt >= vars.actualDebtToLiquidate) {
IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn(
user,
vars.actualDebtToLiquidate,
debtReserve.variableBorrowIndex
);
} else {
// If the user doesn't have variable debt, no need to try to burn variable debt tokens
if (vars.userVariableDebt > 0) {
IVariableDebtToken(debtReserve.variableDebtTokenAddress).burn(
user,
vars.userVariableDebt,
debtReserve.variableBorrowIndex
);
}
IStableDebtToken(debtReserve.stableDebtTokenAddress).burn(
user,
vars.actualDebtToLiquidate.sub(vars.userVariableDebt)
);
}
debtReserve.updateInterestRates(
debtAsset,
debtReserve.aTokenAddress,
vars.actualDebtToLiquidate,
0
);
if (receiveAToken) {
vars.liquidatorPreviousATokenBalance = IERC20(vars.collateralAtoken).balanceOf(msg.sender);
vars.collateralAtoken.transferOnLiquidation(user, msg.sender, vars.maxCollateralToLiquidate);
if (vars.liquidatorPreviousATokenBalance == 0) {
DataTypes.UserConfigurationMap storage liquidatorConfig = _usersConfig[msg.sender];
liquidatorConfig.setUsingAsCollateral(collateralReserve.id, true);
emit ReserveUsedAsCollateralEnabled(collateralAsset, msg.sender);
}
} else {
collateralReserve.updateState();
collateralReserve.updateInterestRates(
collateralAsset,
address(vars.collateralAtoken),
0,
vars.maxCollateralToLiquidate
);
// Burn the equivalent amount of aToken, sending the underlying to the liquidator
vars.collateralAtoken.burn(
user,
msg.sender,
vars.maxCollateralToLiquidate,
collateralReserve.liquidityIndex
);
}
// If the collateral being liquidated is equal to the user balance,
// we set the currency as not being used as collateral anymore
if (vars.maxCollateralToLiquidate == vars.userCollateralBalance) {
userConfig.setUsingAsCollateral(collateralReserve.id, false);
emit ReserveUsedAsCollateralDisabled(collateralAsset, user);
}
// Transfers the debt asset being repaid to the aToken, where the liquidity is kept
IERC20(debtAsset).safeTransferFrom(
msg.sender,
debtReserve.aTokenAddress,
vars.actualDebtToLiquidate
);
emit LiquidationCall(
collateralAsset,
debtAsset,
user,
vars.actualDebtToLiquidate,
vars.maxCollateralToLiquidate,
msg.sender,
receiveAToken
);
return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS);
}
struct AvailableCollateralToLiquidateLocalVars {
uint256 userCompoundedBorrowBalance;
uint256 liquidationBonus;
uint256 collateralPrice;
uint256 debtAssetPrice;
uint256 maxAmountCollateralToLiquidate;
uint256 debtAssetDecimals;
uint256 collateralDecimals;
}
/**
* @dev Calculates how much of a specific collateral can be liquidated, given
* a certain amount of debt asset.
* - This function needs to be called after all the checks to validate the liquidation have been performed,
* otherwise it might fail.
* @param collateralReserve The data of the collateral reserve
* @param debtReserve The data of the debt reserve
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param userCollateralBalance The collateral balance for the specific `collateralAsset` of the user being liquidated
* @return collateralAmount: The maximum amount that is possible to liquidate given all the liquidation constraints
* (user balance, close factor)
* debtAmountNeeded: The amount to repay with the liquidation
**/
function _calculateAvailableCollateralToLiquidate(
DataTypes.ReserveData storage collateralReserve,
DataTypes.ReserveData storage debtReserve,
address collateralAsset,
address debtAsset,
uint256 debtToCover,
uint256 userCollateralBalance
) internal view returns (uint256, uint256) {
uint256 collateralAmount = 0;
uint256 debtAmountNeeded = 0;
IPriceOracleGetter oracle = IPriceOracleGetter(_addressesProvider.getPriceOracle());
AvailableCollateralToLiquidateLocalVars memory vars;
vars.collateralPrice = oracle.getAssetPrice(collateralAsset);
vars.debtAssetPrice = oracle.getAssetPrice(debtAsset);
(, , vars.liquidationBonus, vars.collateralDecimals, ) = collateralReserve
.configuration
.getParams();
vars.debtAssetDecimals = debtReserve.configuration.getDecimals();
// This is the maximum possible amount of the selected collateral that can be liquidated, given the
// max amount of liquidatable debt
vars.maxAmountCollateralToLiquidate = vars
.debtAssetPrice
.mul(debtToCover)
.mul(10**vars.collateralDecimals)
.percentMul(vars.liquidationBonus)
.div(vars.collateralPrice.mul(10**vars.debtAssetDecimals));
if (vars.maxAmountCollateralToLiquidate > userCollateralBalance) {
collateralAmount = userCollateralBalance;
debtAmountNeeded = vars
.collateralPrice
.mul(collateralAmount)
.mul(10**vars.debtAssetDecimals)
.div(vars.debtAssetPrice.mul(10**vars.collateralDecimals))
.percentDiv(vars.liquidationBonus);
} else {
collateralAmount = vars.maxAmountCollateralToLiquidate;
debtAmountNeeded = debtToCover;
}
return (collateralAmount, debtAmountNeeded);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {IScaledBalanceToken} from './IScaledBalanceToken.sol';
import {IInitializableAToken} from './IInitializableAToken.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount being
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints `amount` aTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted after aTokens are burned
* @param from The owner of the aTokens, getting them burned
* @param target The address that will receive the underlying
* @param value The amount being burned
* @param index The new liquidity index of the reserve
**/
event Burn(address indexed from, address indexed target, uint256 value, uint256 index);
/**
* @dev Emitted during the transfer action
* @param from The user whose tokens are being transferred
* @param to The recipient
* @param value The amount being transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(address indexed from, address indexed to, uint256 value, uint256 index);
/**
* @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the aTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints aTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* @param from The address getting liquidated, current owner of the aTokens
* @param to The recipient
* @param value The amount of tokens getting transferred
**/
function transferOnLiquidation(
address from,
address to,
uint256 value
) external;
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the underlying
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount) external returns (uint256);
/**
* @dev Invoked to execute actions on the aToken side after a repayment.
* @param user The user executing the repayment
* @param amount The amount getting repaid
**/
function handleRepayment(address user, uint256 amount) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (IAaveIncentivesController);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IInitializableDebtToken} from './IInitializableDebtToken.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
/**
* @title IStableDebtToken
* @notice Defines the interface for the stable debt token
* @dev It does not inherit from IERC20 to save in code size
* @author Aave
**/
interface IStableDebtToken is IInitializableDebtToken {
/**
* @dev Emitted when new stable debt is minted
* @param user The address of the user who triggered the minting
* @param onBehalfOf The recipient of stable debt tokens
* @param amount The amount minted
* @param currentBalance The current balance of the user
* @param balanceIncrease The increase in balance since the last action of the user
* @param newRate The rate of the debt after the minting
* @param avgStableRate The new average stable rate after the minting
* @param newTotalSupply The new total supply of the stable debt token after the action
**/
event Mint(
address indexed user,
address indexed onBehalfOf,
uint256 amount,
uint256 currentBalance,
uint256 balanceIncrease,
uint256 newRate,
uint256 avgStableRate,
uint256 newTotalSupply
);
/**
* @dev Emitted when new stable debt is burned
* @param user The address of the user
* @param amount The amount being burned
* @param currentBalance The current balance of the user
* @param balanceIncrease The the increase in balance since the last action of the user
* @param avgStableRate The new average stable rate after the burning
* @param newTotalSupply The new total supply of the stable debt token after the action
**/
event Burn(
address indexed user,
uint256 amount,
uint256 currentBalance,
uint256 balanceIncrease,
uint256 avgStableRate,
uint256 newTotalSupply
);
/**
* @dev Mints debt token to the `onBehalfOf` address.
* - The resulting rate is the weighted average between the rate of the new debt
* and the rate of the previous debt
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt tokens to mint
* @param rate The rate of the debt being minted
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 rate
) external returns (bool);
/**
* @dev Burns debt of `user`
* - The resulting rate is the weighted average between the rate of the new debt
* and the rate of the previous debt
* @param user The address of the user getting his debt burned
* @param amount The amount of debt tokens getting burned
**/
function burn(address user, uint256 amount) external;
/**
* @dev Returns the average rate of all the stable rate loans.
* @return The average stable rate
**/
function getAverageStableRate() external view returns (uint256);
/**
* @dev Returns the stable rate of the user debt
* @return The stable rate of the user
**/
function getUserStableRate(address user) external view returns (uint256);
/**
* @dev Returns the timestamp of the last update of the user
* @return The timestamp
**/
function getUserLastUpdated(address user) external view returns (uint40);
/**
* @dev Returns the principal, the total supply and the average stable rate
**/
function getSupplyData()
external
view
returns (
uint256,
uint256,
uint256,
uint40
);
/**
* @dev Returns the timestamp of the last update of the total supply
* @return The timestamp
**/
function getTotalSupplyLastUpdated() external view returns (uint40);
/**
* @dev Returns the total supply and the average stable rate
**/
function getTotalSupplyAndAvgRate() external view returns (uint256, uint256);
/**
* @dev Returns the principal debt balance of the user
* @return The debt balance of the user since the last burn/mint action
**/
function principalBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (IAaveIncentivesController);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IScaledBalanceToken} from './IScaledBalanceToken.sol';
import {IInitializableDebtToken} from './IInitializableDebtToken.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
/**
* @title IVariableDebtToken
* @author Aave
* @notice Defines the basic interface for a variable debt token.
**/
interface IVariableDebtToken is IScaledBalanceToken, IInitializableDebtToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param onBehalfOf The address of the user on which behalf minting has been performed
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(address indexed from, address indexed onBehalfOf, uint256 value, uint256 index);
/**
* @dev Mints debt token to the `onBehalfOf` address
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/**
* @dev Burns user variable debt
* @param user The user which debt is burnt
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view returns (IAaveIncentivesController);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title ILendingPoolCollateralManager
* @author Aave
* @notice Defines the actions involving management of collateral in the protocol.
**/
interface ILendingPoolCollateralManager {
/**
* @dev Emitted when a borrower is liquidated
* @param collateral The address of the collateral being liquidated
* @param principal The address of the reserve
* @param user The address of the user being liquidated
* @param debtToCover The total amount liquidated
* @param liquidatedCollateralAmount The amount of collateral being liquidated
* @param liquidator The address of the liquidator
* @param receiveAToken true if the liquidator wants to receive aTokens, false otherwise
**/
event LiquidationCall(
address indexed collateral,
address indexed principal,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when a reserve is disabled as collateral for an user
* @param reserve The address of the reserve
* @param user The address of the user
**/
event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user);
/**
* @dev Emitted when a reserve is enabled as collateral for an user
* @param reserve The address of the reserve
* @param user The address of the user
**/
event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user);
/**
* @dev Users can invoke this function to liquidate an undercollateralized position.
* @param collateral The address of the collateral to liquidated
* @param principal The address of the principal reserve
* @param user The address of the borrower
* @param debtToCover The amount of principal that the liquidator wants to repay
* @param receiveAToken true if the liquidators wants to receive the aTokens, false if
* he wants to receive the underlying asset directly
**/
function liquidationCall(
address collateral,
address principal,
address user,
uint256 debtToCover,
bool receiveAToken
) external returns (uint256, string memory);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title VersionedInitializable
*
* @dev Helper contract to implement initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*
* @author Aave, inspired by the OpenZeppelin Initializable contract
*/
abstract contract VersionedInitializable {
/**
* @dev Indicates that the contract has been initialized.
*/
uint256 private lastInitializedRevision = 0;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
uint256 revision = getRevision();
require(
initializing || isConstructor() || revision > lastInitializedRevision,
'Contract instance has already been initialized'
);
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
lastInitializedRevision = revision;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/**
* @dev returns the revision number of the contract
* Needs to be defined in the inherited class as a constant.
**/
function getRevision() internal pure virtual returns (uint256);
/**
* @dev Returns true if and only if the function is running in the constructor
**/
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
//solium-disable-next-line
assembly {
cs := extcodesize(address())
}
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import {ReserveLogic} from './ReserveLogic.sol';
import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../configuration/UserConfiguration.sol';
import {WadRayMath} from '../math/WadRayMath.sol';
import {PercentageMath} from '../math/PercentageMath.sol';
import {IPriceOracleGetter} from '../../../interfaces/IPriceOracleGetter.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title GenericLogic library
* @author Aave
* @title Implements protocol-level logic to calculate and validate the state of a user
*/
library GenericLogic {
using ReserveLogic for DataTypes.ReserveData;
using SafeMath for uint256;
using WadRayMath for uint256;
using PercentageMath for uint256;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
uint256 public constant HEALTH_FACTOR_LIQUIDATION_THRESHOLD = 1 ether;
struct balanceDecreaseAllowedLocalVars {
uint256 decimals;
uint256 liquidationThreshold;
uint256 totalCollateralInETH;
uint256 totalDebtInETH;
uint256 avgLiquidationThreshold;
uint256 amountToDecreaseInETH;
uint256 collateralBalanceAfterDecrease;
uint256 liquidationThresholdAfterDecrease;
uint256 healthFactorAfterDecrease;
bool reserveUsageAsCollateralEnabled;
}
/**
* @dev Checks if a specific balance decrease is allowed
* (i.e. doesn't bring the user borrow position health factor under HEALTH_FACTOR_LIQUIDATION_THRESHOLD)
* @param asset The address of the underlying asset of the reserve
* @param user The address of the user
* @param amount The amount to decrease
* @param reservesData The data of all the reserves
* @param userConfig The user configuration
* @param reserves The list of all the active reserves
* @param oracle The address of the oracle contract
* @return true if the decrease of the balance is allowed
**/
function balanceDecreaseAllowed(
address asset,
address user,
uint256 amount,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap calldata userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) external view returns (bool) {
if (!userConfig.isBorrowingAny() || !userConfig.isUsingAsCollateral(reservesData[asset].id)) {
return true;
}
balanceDecreaseAllowedLocalVars memory vars;
(, vars.liquidationThreshold, , vars.decimals, ) = reservesData[asset]
.configuration
.getParams();
if (vars.liquidationThreshold == 0) {
return true;
}
(
vars.totalCollateralInETH,
vars.totalDebtInETH,
,
vars.avgLiquidationThreshold,
) = calculateUserAccountData(user, reservesData, userConfig, reserves, reservesCount, oracle);
if (vars.totalDebtInETH == 0) {
return true;
}
vars.amountToDecreaseInETH = IPriceOracleGetter(oracle).getAssetPrice(asset).mul(amount).div(
10**vars.decimals
);
vars.collateralBalanceAfterDecrease = vars.totalCollateralInETH.sub(vars.amountToDecreaseInETH);
//if there is a borrow, there can't be 0 collateral
if (vars.collateralBalanceAfterDecrease == 0) {
return false;
}
vars.liquidationThresholdAfterDecrease = vars
.totalCollateralInETH
.mul(vars.avgLiquidationThreshold)
.sub(vars.amountToDecreaseInETH.mul(vars.liquidationThreshold))
.div(vars.collateralBalanceAfterDecrease);
uint256 healthFactorAfterDecrease =
calculateHealthFactorFromBalances(
vars.collateralBalanceAfterDecrease,
vars.totalDebtInETH,
vars.liquidationThresholdAfterDecrease
);
return healthFactorAfterDecrease >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD;
}
struct CalculateUserAccountDataVars {
uint256 reserveUnitPrice;
uint256 tokenUnit;
uint256 compoundedLiquidityBalance;
uint256 compoundedBorrowBalance;
uint256 decimals;
uint256 ltv;
uint256 liquidationThreshold;
uint256 i;
uint256 healthFactor;
uint256 totalCollateralInETH;
uint256 totalDebtInETH;
uint256 avgLtv;
uint256 avgLiquidationThreshold;
uint256 reservesLength;
bool healthFactorBelowThreshold;
address currentReserveAddress;
bool usageAsCollateralEnabled;
bool userUsesReserveAsCollateral;
}
/**
* @dev Calculates the user data across the reserves.
* this includes the total liquidity/collateral/borrow balances in ETH,
* the average Loan To Value, the average Liquidation Ratio, and the Health factor.
* @param user The address of the user
* @param reservesData Data of all the reserves
* @param userConfig The configuration of the user
* @param reserves The list of the available reserves
* @param oracle The price oracle address
* @return The total collateral and total debt of the user in ETH, the avg ltv, liquidation threshold and the HF
**/
function calculateUserAccountData(
address user,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap memory userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
)
internal
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
CalculateUserAccountDataVars memory vars;
if (userConfig.isEmpty()) {
return (0, 0, 0, 0, uint256(-1));
}
for (vars.i = 0; vars.i < reservesCount; vars.i++) {
if (!userConfig.isUsingAsCollateralOrBorrowing(vars.i)) {
continue;
}
vars.currentReserveAddress = reserves[vars.i];
DataTypes.ReserveData storage currentReserve = reservesData[vars.currentReserveAddress];
(vars.ltv, vars.liquidationThreshold, , vars.decimals, ) = currentReserve
.configuration
.getParams();
vars.tokenUnit = 10**vars.decimals;
vars.reserveUnitPrice = IPriceOracleGetter(oracle).getAssetPrice(vars.currentReserveAddress);
if (vars.liquidationThreshold != 0 && userConfig.isUsingAsCollateral(vars.i)) {
vars.compoundedLiquidityBalance = IERC20(currentReserve.aTokenAddress).balanceOf(user);
uint256 liquidityBalanceETH =
vars.reserveUnitPrice.mul(vars.compoundedLiquidityBalance).div(vars.tokenUnit);
vars.totalCollateralInETH = vars.totalCollateralInETH.add(liquidityBalanceETH);
vars.avgLtv = vars.avgLtv.add(liquidityBalanceETH.mul(vars.ltv));
vars.avgLiquidationThreshold = vars.avgLiquidationThreshold.add(
liquidityBalanceETH.mul(vars.liquidationThreshold)
);
}
if (userConfig.isBorrowing(vars.i)) {
vars.compoundedBorrowBalance = IERC20(currentReserve.stableDebtTokenAddress).balanceOf(
user
);
vars.compoundedBorrowBalance = vars.compoundedBorrowBalance.add(
IERC20(currentReserve.variableDebtTokenAddress).balanceOf(user)
);
vars.totalDebtInETH = vars.totalDebtInETH.add(
vars.reserveUnitPrice.mul(vars.compoundedBorrowBalance).div(vars.tokenUnit)
);
}
}
vars.avgLtv = vars.totalCollateralInETH > 0 ? vars.avgLtv.div(vars.totalCollateralInETH) : 0;
vars.avgLiquidationThreshold = vars.totalCollateralInETH > 0
? vars.avgLiquidationThreshold.div(vars.totalCollateralInETH)
: 0;
vars.healthFactor = calculateHealthFactorFromBalances(
vars.totalCollateralInETH,
vars.totalDebtInETH,
vars.avgLiquidationThreshold
);
return (
vars.totalCollateralInETH,
vars.totalDebtInETH,
vars.avgLtv,
vars.avgLiquidationThreshold,
vars.healthFactor
);
}
/**
* @dev Calculates the health factor from the corresponding balances
* @param totalCollateralInETH The total collateral in ETH
* @param totalDebtInETH The total debt in ETH
* @param liquidationThreshold The avg liquidation threshold
* @return The health factor calculated from the balances provided
**/
function calculateHealthFactorFromBalances(
uint256 totalCollateralInETH,
uint256 totalDebtInETH,
uint256 liquidationThreshold
) internal pure returns (uint256) {
if (totalDebtInETH == 0) return uint256(-1);
return (totalCollateralInETH.percentMul(liquidationThreshold)).wadDiv(totalDebtInETH);
}
/**
* @dev Calculates the equivalent amount in ETH that an user can borrow, depending on the available collateral and the
* average Loan To Value
* @param totalCollateralInETH The total collateral in ETH
* @param totalDebtInETH The total borrow balance
* @param ltv The average loan to value
* @return the amount available to borrow in ETH for the user
**/
function calculateAvailableBorrowsETH(
uint256 totalCollateralInETH,
uint256 totalDebtInETH,
uint256 ltv
) internal pure returns (uint256) {
uint256 availableBorrowsETH = totalCollateralInETH.percentMul(ltv);
if (availableBorrowsETH < totalDebtInETH) {
return 0;
}
availableBorrowsETH = availableBorrowsETH.sub(totalDebtInETH);
return availableBorrowsETH;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title Helpers library
* @author Aave
*/
library Helpers {
/**
* @dev Fetches the user current stable and variable debt balances
* @param user The user address
* @param reserve The reserve data object
* @return The stable and variable debt balance
**/
function getUserCurrentDebt(address user, DataTypes.ReserveData storage reserve)
internal
view
returns (uint256, uint256)
{
return (
IERC20(reserve.stableDebtTokenAddress).balanceOf(user),
IERC20(reserve.variableDebtTokenAddress).balanceOf(user)
);
}
function getUserCurrentDebtMemory(address user, DataTypes.ReserveData memory reserve)
internal
view
returns (uint256, uint256)
{
return (
IERC20(reserve.stableDebtTokenAddress).balanceOf(user),
IERC20(reserve.variableDebtTokenAddress).balanceOf(user)
);
}
}
// 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;
pragma experimental ABIEncoderV2;
import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import {ReserveLogic} from './ReserveLogic.sol';
import {GenericLogic} from './GenericLogic.sol';
import {WadRayMath} from '../math/WadRayMath.sol';
import {PercentageMath} from '../math/PercentageMath.sol';
import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../configuration/UserConfiguration.sol';
import {Errors} from '../helpers/Errors.sol';
import {Helpers} from '../helpers/Helpers.sol';
import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title ReserveLogic library
* @author Aave
* @notice Implements functions to validate the different actions of the protocol
*/
library ValidationLogic {
using ReserveLogic for DataTypes.ReserveData;
using SafeMath for uint256;
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20 for IERC20;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
uint256 public constant REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD = 4000;
uint256 public constant REBALANCE_UP_USAGE_RATIO_THRESHOLD = 0.95 * 1e27; //usage ratio of 95%
/**
* @dev Validates a deposit action
* @param reserve The reserve object on which the user is depositing
* @param amount The amount to be deposited
*/
function validateDeposit(DataTypes.ReserveData storage reserve, uint256 amount) external view {
(bool isActive, bool isFrozen, , ) = reserve.configuration.getFlags();
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!isFrozen, Errors.VL_RESERVE_FROZEN);
}
/**
* @dev Validates a withdraw action
* @param reserveAddress The address of the reserve
* @param amount The amount to be withdrawn
* @param userBalance The balance of the user
* @param reservesData The reserves state
* @param userConfig The user configuration
* @param reserves The addresses of the reserves
* @param reservesCount The number of reserves
* @param oracle The price oracle
*/
function validateWithdraw(
address reserveAddress,
uint256 amount,
uint256 userBalance,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) external view {
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(amount <= userBalance, Errors.VL_NOT_ENOUGH_AVAILABLE_USER_BALANCE);
(bool isActive, , , ) = reservesData[reserveAddress].configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(
GenericLogic.balanceDecreaseAllowed(
reserveAddress,
msg.sender,
amount,
reservesData,
userConfig,
reserves,
reservesCount,
oracle
),
Errors.VL_TRANSFER_NOT_ALLOWED
);
}
struct ValidateBorrowLocalVars {
uint256 currentLtv;
uint256 currentLiquidationThreshold;
uint256 amountOfCollateralNeededETH;
uint256 userCollateralBalanceETH;
uint256 userBorrowBalanceETH;
uint256 availableLiquidity;
uint256 healthFactor;
bool isActive;
bool isFrozen;
bool borrowingEnabled;
bool stableRateBorrowingEnabled;
}
/**
* @dev Validates a borrow action
* @param asset The address of the asset to borrow
* @param reserve The reserve state from which the user is borrowing
* @param userAddress The address of the user
* @param amount The amount to be borrowed
* @param amountInETH The amount to be borrowed, in ETH
* @param interestRateMode The interest rate mode at which the user is borrowing
* @param maxStableLoanPercent The max amount of the liquidity that can be borrowed at stable rate, in percentage
* @param reservesData The state of all the reserves
* @param userConfig The state of the user for the specific reserve
* @param reserves The addresses of all the active reserves
* @param oracle The price oracle
*/
function validateBorrow(
address asset,
DataTypes.ReserveData storage reserve,
address userAddress,
uint256 amount,
uint256 amountInETH,
uint256 interestRateMode,
uint256 maxStableLoanPercent,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) external view {
ValidateBorrowLocalVars memory vars;
(vars.isActive, vars.isFrozen, vars.borrowingEnabled, vars.stableRateBorrowingEnabled) = reserve
.configuration
.getFlags();
require(vars.isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!vars.isFrozen, Errors.VL_RESERVE_FROZEN);
require(amount != 0, Errors.VL_INVALID_AMOUNT);
require(vars.borrowingEnabled, Errors.VL_BORROWING_NOT_ENABLED);
//validate interest rate mode
require(
uint256(DataTypes.InterestRateMode.VARIABLE) == interestRateMode ||
uint256(DataTypes.InterestRateMode.STABLE) == interestRateMode,
Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED
);
(
vars.userCollateralBalanceETH,
vars.userBorrowBalanceETH,
vars.currentLtv,
vars.currentLiquidationThreshold,
vars.healthFactor
) = GenericLogic.calculateUserAccountData(
userAddress,
reservesData,
userConfig,
reserves,
reservesCount,
oracle
);
require(vars.userCollateralBalanceETH > 0, Errors.VL_COLLATERAL_BALANCE_IS_0);
require(
vars.healthFactor > GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,
Errors.VL_HEALTH_FACTOR_LOWER_THAN_LIQUIDATION_THRESHOLD
);
//add the current already borrowed amount to the amount requested to calculate the total collateral needed.
vars.amountOfCollateralNeededETH = vars.userBorrowBalanceETH.add(amountInETH).percentDiv(
vars.currentLtv
); //LTV is calculated in percentage
require(
vars.amountOfCollateralNeededETH <= vars.userCollateralBalanceETH,
Errors.VL_COLLATERAL_CANNOT_COVER_NEW_BORROW
);
/**
* Following conditions need to be met if the user is borrowing at a stable rate:
* 1. Reserve must be enabled for stable rate borrowing
* 2. Users cannot borrow from the reserve if their collateral is (mostly) the same currency
* they are borrowing, to prevent abuses.
* 3. Users will be able to borrow only a portion of the total available liquidity
**/
if (interestRateMode == uint256(DataTypes.InterestRateMode.STABLE)) {
//check if the borrow mode is stable and if stable rate borrowing is enabled on this reserve
require(vars.stableRateBorrowingEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED);
require(
!userConfig.isUsingAsCollateral(reserve.id) ||
reserve.configuration.getLtv() == 0 ||
amount > IERC20(reserve.aTokenAddress).balanceOf(userAddress),
Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY
);
vars.availableLiquidity = IERC20(asset).balanceOf(reserve.aTokenAddress);
//calculate the max available loan size in stable rate mode as a percentage of the
//available liquidity
uint256 maxLoanSizeStable = vars.availableLiquidity.percentMul(maxStableLoanPercent);
require(amount <= maxLoanSizeStable, Errors.VL_AMOUNT_BIGGER_THAN_MAX_LOAN_SIZE_STABLE);
}
}
/**
* @dev Validates a repay action
* @param reserve The reserve state from which the user is repaying
* @param amountSent The amount sent for the repayment. Can be an actual value or uint(-1)
* @param onBehalfOf The address of the user msg.sender is repaying for
* @param stableDebt The borrow balance of the user
* @param variableDebt The borrow balance of the user
*/
function validateRepay(
DataTypes.ReserveData storage reserve,
uint256 amountSent,
DataTypes.InterestRateMode rateMode,
address onBehalfOf,
uint256 stableDebt,
uint256 variableDebt
) external view {
bool isActive = reserve.configuration.getActive();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(amountSent > 0, Errors.VL_INVALID_AMOUNT);
require(
(stableDebt > 0 &&
DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE) ||
(variableDebt > 0 &&
DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.VARIABLE),
Errors.VL_NO_DEBT_OF_SELECTED_TYPE
);
require(
amountSent != uint256(-1) || msg.sender == onBehalfOf,
Errors.VL_NO_EXPLICIT_AMOUNT_TO_REPAY_ON_BEHALF
);
}
/**
* @dev Validates a swap of borrow rate mode.
* @param reserve The reserve state on which the user is swapping the rate
* @param userConfig The user reserves configuration
* @param stableDebt The stable debt of the user
* @param variableDebt The variable debt of the user
* @param currentRateMode The rate mode of the borrow
*/
function validateSwapRateMode(
DataTypes.ReserveData storage reserve,
DataTypes.UserConfigurationMap storage userConfig,
uint256 stableDebt,
uint256 variableDebt,
DataTypes.InterestRateMode currentRateMode
) external view {
(bool isActive, bool isFrozen, , bool stableRateEnabled) = reserve.configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
require(!isFrozen, Errors.VL_RESERVE_FROZEN);
if (currentRateMode == DataTypes.InterestRateMode.STABLE) {
require(stableDebt > 0, Errors.VL_NO_STABLE_RATE_LOAN_IN_RESERVE);
} else if (currentRateMode == DataTypes.InterestRateMode.VARIABLE) {
require(variableDebt > 0, Errors.VL_NO_VARIABLE_RATE_LOAN_IN_RESERVE);
/**
* user wants to swap to stable, before swapping we need to ensure that
* 1. stable borrow rate is enabled on the reserve
* 2. user is not trying to abuse the reserve by depositing
* more collateral than he is borrowing, artificially lowering
* the interest rate, borrowing at variable, and switching to stable
**/
require(stableRateEnabled, Errors.VL_STABLE_BORROWING_NOT_ENABLED);
require(
!userConfig.isUsingAsCollateral(reserve.id) ||
reserve.configuration.getLtv() == 0 ||
stableDebt.add(variableDebt) > IERC20(reserve.aTokenAddress).balanceOf(msg.sender),
Errors.VL_COLLATERAL_SAME_AS_BORROWING_CURRENCY
);
} else {
revert(Errors.VL_INVALID_INTEREST_RATE_MODE_SELECTED);
}
}
/**
* @dev Validates a stable borrow rate rebalance action
* @param reserve The reserve state on which the user is getting rebalanced
* @param reserveAddress The address of the reserve
* @param stableDebtToken The stable debt token instance
* @param variableDebtToken The variable debt token instance
* @param aTokenAddress The address of the aToken contract
*/
function validateRebalanceStableBorrowRate(
DataTypes.ReserveData storage reserve,
address reserveAddress,
IERC20 stableDebtToken,
IERC20 variableDebtToken,
address aTokenAddress
) external view {
(bool isActive, , , ) = reserve.configuration.getFlags();
require(isActive, Errors.VL_NO_ACTIVE_RESERVE);
//if the usage ratio is below 95%, no rebalances are needed
uint256 totalDebt =
stableDebtToken.totalSupply().add(variableDebtToken.totalSupply()).wadToRay();
uint256 availableLiquidity = IERC20(reserveAddress).balanceOf(aTokenAddress).wadToRay();
uint256 usageRatio = totalDebt == 0 ? 0 : totalDebt.rayDiv(availableLiquidity.add(totalDebt));
//if the liquidity rate is below REBALANCE_UP_THRESHOLD of the max variable APR at 95% usage,
//then we allow rebalancing of the stable rate positions.
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 maxVariableBorrowRate =
IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).getMaxVariableBorrowRate();
require(
usageRatio >= REBALANCE_UP_USAGE_RATIO_THRESHOLD &&
currentLiquidityRate <=
maxVariableBorrowRate.percentMul(REBALANCE_UP_LIQUIDITY_RATE_THRESHOLD),
Errors.LP_INTEREST_RATE_REBALANCE_CONDITIONS_NOT_MET
);
}
/**
* @dev Validates the action of setting an asset as collateral
* @param reserve The state of the reserve that the user is enabling or disabling as collateral
* @param reserveAddress The address of the reserve
* @param reservesData The data of all the reserves
* @param userConfig The state of the user for the specific reserve
* @param reserves The addresses of all the active reserves
* @param oracle The price oracle
*/
function validateSetUseReserveAsCollateral(
DataTypes.ReserveData storage reserve,
address reserveAddress,
bool useAsCollateral,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) external view {
uint256 underlyingBalance = IERC20(reserve.aTokenAddress).balanceOf(msg.sender);
require(underlyingBalance > 0, Errors.VL_UNDERLYING_BALANCE_NOT_GREATER_THAN_0);
require(
useAsCollateral ||
GenericLogic.balanceDecreaseAllowed(
reserveAddress,
msg.sender,
underlyingBalance,
reservesData,
userConfig,
reserves,
reservesCount,
oracle
),
Errors.VL_DEPOSIT_ALREADY_IN_USE
);
}
/**
* @dev Validates a flashloan action
* @param assets The assets being flashborrowed
* @param amounts The amounts for each asset being borrowed
**/
function validateFlashloan(address[] memory assets, uint256[] memory amounts) internal pure {
require(assets.length == amounts.length, Errors.VL_INCONSISTENT_FLASHLOAN_PARAMS);
}
/**
* @dev Validates the liquidation action
* @param collateralReserve The reserve data of the collateral
* @param principalReserve The reserve data of the principal
* @param userConfig The user configuration
* @param userHealthFactor The user's health factor
* @param userStableDebt Total stable debt balance of the user
* @param userVariableDebt Total variable debt balance of the user
**/
function validateLiquidationCall(
DataTypes.ReserveData storage collateralReserve,
DataTypes.ReserveData storage principalReserve,
DataTypes.UserConfigurationMap storage userConfig,
uint256 userHealthFactor,
uint256 userStableDebt,
uint256 userVariableDebt
) internal view returns (uint256, string memory) {
if (
!collateralReserve.configuration.getActive() || !principalReserve.configuration.getActive()
) {
return (
uint256(Errors.CollateralManagerErrors.NO_ACTIVE_RESERVE),
Errors.VL_NO_ACTIVE_RESERVE
);
}
if (userHealthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD) {
return (
uint256(Errors.CollateralManagerErrors.HEALTH_FACTOR_ABOVE_THRESHOLD),
Errors.LPCM_HEALTH_FACTOR_NOT_BELOW_THRESHOLD
);
}
bool isCollateralEnabled =
collateralReserve.configuration.getLiquidationThreshold() > 0 &&
userConfig.isUsingAsCollateral(collateralReserve.id);
//if collateral isn't enabled as collateral by user, it cannot be liquidated
if (!isCollateralEnabled) {
return (
uint256(Errors.CollateralManagerErrors.COLLATERAL_CANNOT_BE_LIQUIDATED),
Errors.LPCM_COLLATERAL_CANNOT_BE_LIQUIDATED
);
}
if (userStableDebt == 0 && userVariableDebt == 0) {
return (
uint256(Errors.CollateralManagerErrors.CURRRENCY_NOT_BORROWED),
Errors.LPCM_SPECIFIED_CURRENCY_NOT_BORROWED_BY_USER
);
}
return (uint256(Errors.CollateralManagerErrors.NO_ERROR), Errors.LPCM_NO_ERRORS);
}
/**
* @dev Validates an aToken transfer
* @param from The user from which the aTokens are being transferred
* @param reservesData The state of all the reserves
* @param userConfig The state of the user for the specific reserve
* @param reserves The addresses of all the active reserves
* @param oracle The price oracle
*/
function validateTransfer(
address from,
mapping(address => DataTypes.ReserveData) storage reservesData,
DataTypes.UserConfigurationMap storage userConfig,
mapping(uint256 => address) storage reserves,
uint256 reservesCount,
address oracle
) internal view {
(, , , , uint256 healthFactor) =
GenericLogic.calculateUserAccountData(
from,
reservesData,
userConfig,
reserves,
reservesCount,
oracle
);
require(
healthFactor >= GenericLogic.HEALTH_FACTOR_LIQUIDATION_THRESHOLD,
Errors.VL_TRANSFER_NOT_ALLOWED
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol';
import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';
import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {DataTypes} from '../libraries/types/DataTypes.sol';
contract LendingPoolStorage {
using ReserveLogic for DataTypes.ReserveData;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
ILendingPoolAddressesProvider internal _addressesProvider;
mapping(address => DataTypes.ReserveData) internal _reserves;
mapping(address => DataTypes.UserConfigurationMap) internal _usersConfig;
// the list of the available reserves, structured as a mapping for gas savings reasons
mapping(uint256 => address) internal _reservesList;
uint256 internal _reservesCount;
bool internal _paused;
uint256 internal _maxStableRateBorrowSizePercent;
uint256 internal _flashLoanPremiumTotal;
uint256 internal _maxNumberOfReserves;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingPool} from './ILendingPool.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
/**
* @title IInitializableAToken
* @notice Interface for the initialize function on AToken
* @author Aave
**/
interface IInitializableAToken {
/**
* @dev Emitted when an aToken is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param treasury The address of the treasury
* @param incentivesController The address of the incentives controller for this aToken
* @param aTokenDecimals the decimals of the underlying
* @param aTokenName the name of the aToken
* @param aTokenSymbol the symbol of the aToken
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address treasury,
address incentivesController,
uint8 aTokenDecimals,
string aTokenName,
string aTokenSymbol,
bytes params
);
/**
* @dev Initializes the aToken
* @param pool The address of the lending pool where this aToken will be used
* @param treasury The address of the Aave treasury, receiving the fees on this aToken
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param aTokenDecimals The decimals of the aToken, same as the underlying asset's
* @param aTokenName The name of the aToken
* @param aTokenSymbol The symbol of the aToken
*/
function initialize(
ILendingPool pool,
address treasury,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 aTokenDecimals,
string calldata aTokenName,
string calldata aTokenSymbol,
bytes calldata params
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IAaveIncentivesController {
function handleAction(
address user,
uint256 userBalance,
uint256 totalSupply
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingPool} from './ILendingPool.sol';
import {IAaveIncentivesController} from './IAaveIncentivesController.sol';
/**
* @title IInitializableDebtToken
* @notice Interface for the initialize function common between debt tokens
* @author Aave
**/
interface IInitializableDebtToken {
/**
* @dev Emitted when a debt token is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param incentivesController The address of the incentives controller for this aToken
* @param debtTokenDecimals the decimals of the debt token
* @param debtTokenName the name of the debt token
* @param debtTokenSymbol the symbol of the debt token
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address incentivesController,
uint8 debtTokenDecimals,
string debtTokenName,
string debtTokenSymbol,
bytes params
);
/**
* @dev Initializes the debt token.
* @param pool The address of the lending pool where this aToken will be used
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's
* @param debtTokenName The name of the token
* @param debtTokenSymbol The symbol of the token
*/
function initialize(
ILendingPool pool,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../../dependencies/openzeppelin/contracts/IERC20.sol';
import {SafeERC20} from '../../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {IAToken} from '../../../interfaces/IAToken.sol';
import {IStableDebtToken} from '../../../interfaces/IStableDebtToken.sol';
import {IVariableDebtToken} from '../../../interfaces/IVariableDebtToken.sol';
import {IReserveInterestRateStrategy} from '../../../interfaces/IReserveInterestRateStrategy.sol';
import {ReserveConfiguration} from '../configuration/ReserveConfiguration.sol';
import {MathUtils} from '../math/MathUtils.sol';
import {WadRayMath} from '../math/WadRayMath.sol';
import {PercentageMath} from '../math/PercentageMath.sol';
import {Errors} from '../helpers/Errors.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title ReserveLogic library
* @author Aave
* @notice Implements the logic to update the reserves state
*/
library ReserveLogic {
using SafeMath for uint256;
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Emitted when the state of a reserve is updated
* @param asset The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed asset,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
using ReserveLogic for DataTypes.ReserveData;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
/**
* @dev Returns the ongoing normalized income for the reserve
* A value of 1e27 means there is no income. As time passes, the income is accrued
* A value of 2*1e27 means for each unit of asset one unit of income has been accrued
* @param reserve The reserve object
* @return the normalized income. expressed in ray
**/
function getNormalizedIncome(DataTypes.ReserveData storage reserve)
internal
view
returns (uint256)
{
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.liquidityIndex;
}
uint256 cumulated =
MathUtils.calculateLinearInterest(reserve.currentLiquidityRate, timestamp).rayMul(
reserve.liquidityIndex
);
return cumulated;
}
/**
* @dev Returns the ongoing normalized variable debt for the reserve
* A value of 1e27 means there is no debt. As time passes, the income is accrued
* A value of 2*1e27 means that for each unit of debt, one unit worth of interest has been accumulated
* @param reserve The reserve object
* @return The normalized variable debt. expressed in ray
**/
function getNormalizedDebt(DataTypes.ReserveData storage reserve)
internal
view
returns (uint256)
{
uint40 timestamp = reserve.lastUpdateTimestamp;
//solium-disable-next-line
if (timestamp == uint40(block.timestamp)) {
//if the index was updated in the same block, no need to perform any calculation
return reserve.variableBorrowIndex;
}
uint256 cumulated =
MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp).rayMul(
reserve.variableBorrowIndex
);
return cumulated;
}
/**
* @dev Updates the liquidity cumulative index and the variable borrow index.
* @param reserve the reserve object
**/
function updateState(DataTypes.ReserveData storage reserve) internal {
uint256 scaledVariableDebt =
IVariableDebtToken(reserve.variableDebtTokenAddress).scaledTotalSupply();
uint256 previousVariableBorrowIndex = reserve.variableBorrowIndex;
uint256 previousLiquidityIndex = reserve.liquidityIndex;
uint40 lastUpdatedTimestamp = reserve.lastUpdateTimestamp;
(uint256 newLiquidityIndex, uint256 newVariableBorrowIndex) =
_updateIndexes(
reserve,
scaledVariableDebt,
previousLiquidityIndex,
previousVariableBorrowIndex,
lastUpdatedTimestamp
);
_mintToTreasury(
reserve,
scaledVariableDebt,
previousVariableBorrowIndex,
newLiquidityIndex,
newVariableBorrowIndex,
lastUpdatedTimestamp
);
}
/**
* @dev Accumulates a predefined amount of asset to the reserve as a fixed, instantaneous income. Used for example to accumulate
* the flashloan fee to the reserve, and spread it between all the depositors
* @param reserve The reserve object
* @param totalLiquidity The total liquidity available in the reserve
* @param amount The amount to accomulate
**/
function cumulateToLiquidityIndex(
DataTypes.ReserveData storage reserve,
uint256 totalLiquidity,
uint256 amount
) internal {
uint256 amountToLiquidityRatio = amount.wadToRay().rayDiv(totalLiquidity.wadToRay());
uint256 result = amountToLiquidityRatio.add(WadRayMath.ray());
result = result.rayMul(reserve.liquidityIndex);
require(result <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);
reserve.liquidityIndex = uint128(result);
}
/**
* @dev Initializes a reserve
* @param reserve The reserve object
* @param aTokenAddress The address of the overlying atoken contract
* @param interestRateStrategyAddress The address of the interest rate strategy contract
**/
function init(
DataTypes.ReserveData storage reserve,
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress,
address interestRateStrategyAddress
) external {
require(reserve.aTokenAddress == address(0), Errors.RL_RESERVE_ALREADY_INITIALIZED);
reserve.liquidityIndex = uint128(WadRayMath.ray());
reserve.variableBorrowIndex = uint128(WadRayMath.ray());
reserve.aTokenAddress = aTokenAddress;
reserve.stableDebtTokenAddress = stableDebtTokenAddress;
reserve.variableDebtTokenAddress = variableDebtTokenAddress;
reserve.interestRateStrategyAddress = interestRateStrategyAddress;
}
struct UpdateInterestRatesLocalVars {
address stableDebtTokenAddress;
uint256 availableLiquidity;
uint256 totalStableDebt;
uint256 newLiquidityRate;
uint256 newStableRate;
uint256 newVariableRate;
uint256 avgStableRate;
uint256 totalVariableDebt;
}
/**
* @dev Updates the reserve current stable borrow rate, the current variable borrow rate and the current liquidity rate
* @param reserve The address of the reserve to be updated
* @param liquidityAdded The amount of liquidity added to the protocol (deposit or repay) in the previous action
* @param liquidityTaken The amount of liquidity taken from the protocol (redeem or borrow)
**/
function updateInterestRates(
DataTypes.ReserveData storage reserve,
address reserveAddress,
address aTokenAddress,
uint256 liquidityAdded,
uint256 liquidityTaken
) internal {
UpdateInterestRatesLocalVars memory vars;
vars.stableDebtTokenAddress = reserve.stableDebtTokenAddress;
(vars.totalStableDebt, vars.avgStableRate) = IStableDebtToken(vars.stableDebtTokenAddress)
.getTotalSupplyAndAvgRate();
//calculates the total variable debt locally using the scaled total supply instead
//of totalSupply(), as it's noticeably cheaper. Also, the index has been
//updated by the previous updateState() call
vars.totalVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress)
.scaledTotalSupply()
.rayMul(reserve.variableBorrowIndex);
(
vars.newLiquidityRate,
vars.newStableRate,
vars.newVariableRate
) = IReserveInterestRateStrategy(reserve.interestRateStrategyAddress).calculateInterestRates(
reserveAddress,
aTokenAddress,
liquidityAdded,
liquidityTaken,
vars.totalStableDebt,
vars.totalVariableDebt,
vars.avgStableRate,
reserve.configuration.getReserveFactor()
);
require(vars.newLiquidityRate <= type(uint128).max, Errors.RL_LIQUIDITY_RATE_OVERFLOW);
require(vars.newStableRate <= type(uint128).max, Errors.RL_STABLE_BORROW_RATE_OVERFLOW);
require(vars.newVariableRate <= type(uint128).max, Errors.RL_VARIABLE_BORROW_RATE_OVERFLOW);
reserve.currentLiquidityRate = uint128(vars.newLiquidityRate);
reserve.currentStableBorrowRate = uint128(vars.newStableRate);
reserve.currentVariableBorrowRate = uint128(vars.newVariableRate);
emit ReserveDataUpdated(
reserveAddress,
vars.newLiquidityRate,
vars.newStableRate,
vars.newVariableRate,
reserve.liquidityIndex,
reserve.variableBorrowIndex
);
}
struct MintToTreasuryLocalVars {
uint256 currentStableDebt;
uint256 principalStableDebt;
uint256 previousStableDebt;
uint256 currentVariableDebt;
uint256 previousVariableDebt;
uint256 avgStableRate;
uint256 cumulatedStableInterest;
uint256 totalDebtAccrued;
uint256 amountToMint;
uint256 reserveFactor;
uint40 stableSupplyUpdatedTimestamp;
}
/**
* @dev Mints part of the repaid interest to the reserve treasury as a function of the reserveFactor for the
* specific asset.
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The current scaled total variable debt
* @param previousVariableBorrowIndex The variable borrow index before the last accumulation of the interest
* @param newLiquidityIndex The new liquidity index
* @param newVariableBorrowIndex The variable borrow index after the last accumulation of the interest
**/
function _mintToTreasury(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 previousVariableBorrowIndex,
uint256 newLiquidityIndex,
uint256 newVariableBorrowIndex,
uint40 timestamp
) internal {
MintToTreasuryLocalVars memory vars;
vars.reserveFactor = reserve.configuration.getReserveFactor();
if (vars.reserveFactor == 0) {
return;
}
//fetching the principal, total stable debt and the avg stable rate
(
vars.principalStableDebt,
vars.currentStableDebt,
vars.avgStableRate,
vars.stableSupplyUpdatedTimestamp
) = IStableDebtToken(reserve.stableDebtTokenAddress).getSupplyData();
//calculate the last principal variable debt
vars.previousVariableDebt = scaledVariableDebt.rayMul(previousVariableBorrowIndex);
//calculate the new total supply after accumulation of the index
vars.currentVariableDebt = scaledVariableDebt.rayMul(newVariableBorrowIndex);
//calculate the stable debt until the last timestamp update
vars.cumulatedStableInterest = MathUtils.calculateCompoundedInterest(
vars.avgStableRate,
vars.stableSupplyUpdatedTimestamp,
timestamp
);
vars.previousStableDebt = vars.principalStableDebt.rayMul(vars.cumulatedStableInterest);
//debt accrued is the sum of the current debt minus the sum of the debt at the last update
vars.totalDebtAccrued = vars
.currentVariableDebt
.add(vars.currentStableDebt)
.sub(vars.previousVariableDebt)
.sub(vars.previousStableDebt);
vars.amountToMint = vars.totalDebtAccrued.percentMul(vars.reserveFactor);
if (vars.amountToMint != 0) {
IAToken(reserve.aTokenAddress).mintToTreasury(vars.amountToMint, newLiquidityIndex);
}
}
/**
* @dev Updates the reserve indexes and the timestamp of the update
* @param reserve The reserve reserve to be updated
* @param scaledVariableDebt The scaled variable debt
* @param liquidityIndex The last stored liquidity index
* @param variableBorrowIndex The last stored variable borrow index
**/
function _updateIndexes(
DataTypes.ReserveData storage reserve,
uint256 scaledVariableDebt,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 timestamp
) internal returns (uint256, uint256) {
uint256 currentLiquidityRate = reserve.currentLiquidityRate;
uint256 newLiquidityIndex = liquidityIndex;
uint256 newVariableBorrowIndex = variableBorrowIndex;
//only cumulating if there is any income being produced
if (currentLiquidityRate > 0) {
uint256 cumulatedLiquidityInterest =
MathUtils.calculateLinearInterest(currentLiquidityRate, timestamp);
newLiquidityIndex = cumulatedLiquidityInterest.rayMul(liquidityIndex);
require(newLiquidityIndex <= type(uint128).max, Errors.RL_LIQUIDITY_INDEX_OVERFLOW);
reserve.liquidityIndex = uint128(newLiquidityIndex);
//as the liquidity rate might come only from stable rate loans, we need to ensure
//that there is actual variable debt before accumulating
if (scaledVariableDebt != 0) {
uint256 cumulatedVariableBorrowInterest =
MathUtils.calculateCompoundedInterest(reserve.currentVariableBorrowRate, timestamp);
newVariableBorrowIndex = cumulatedVariableBorrowInterest.rayMul(variableBorrowIndex);
require(
newVariableBorrowIndex <= type(uint128).max,
Errors.RL_VARIABLE_BORROW_INDEX_OVERFLOW
);
reserve.variableBorrowIndex = uint128(newVariableBorrowIndex);
}
}
//solium-disable-next-line
reserve.lastUpdateTimestamp = uint40(block.timestamp);
return (newLiquidityIndex, newVariableBorrowIndex);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Errors} from '../helpers/Errors.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title ReserveConfiguration library
* @author Aave
* @notice Implements the bitmap logic to handle the reserve configuration
*/
library ReserveConfiguration {
uint256 constant LTV_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000; // prettier-ignore
uint256 constant LIQUIDATION_THRESHOLD_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFF; // prettier-ignore
uint256 constant LIQUIDATION_BONUS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFF; // prettier-ignore
uint256 constant DECIMALS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00FFFFFFFFFFFF; // prettier-ignore
uint256 constant ACTIVE_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant FROZEN_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFBFFFFFFFFFFFFFF; // prettier-ignore
uint256 constant STABLE_BORROWING_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFFFFF; // prettier-ignore
uint256 constant RESERVE_FACTOR_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF0000FFFFFFFFFFFFFFFF; // prettier-ignore
/// @dev For the LTV, the start bit is 0 (up to 15), hence no bitshifting is needed
uint256 constant LIQUIDATION_THRESHOLD_START_BIT_POSITION = 16;
uint256 constant LIQUIDATION_BONUS_START_BIT_POSITION = 32;
uint256 constant RESERVE_DECIMALS_START_BIT_POSITION = 48;
uint256 constant IS_ACTIVE_START_BIT_POSITION = 56;
uint256 constant IS_FROZEN_START_BIT_POSITION = 57;
uint256 constant BORROWING_ENABLED_START_BIT_POSITION = 58;
uint256 constant STABLE_BORROWING_ENABLED_START_BIT_POSITION = 59;
uint256 constant RESERVE_FACTOR_START_BIT_POSITION = 64;
uint256 constant MAX_VALID_LTV = 65535;
uint256 constant MAX_VALID_LIQUIDATION_THRESHOLD = 65535;
uint256 constant MAX_VALID_LIQUIDATION_BONUS = 65535;
uint256 constant MAX_VALID_DECIMALS = 255;
uint256 constant MAX_VALID_RESERVE_FACTOR = 65535;
/**
* @dev Sets the Loan to Value of the reserve
* @param self The reserve configuration
* @param ltv the new ltv
**/
function setLtv(DataTypes.ReserveConfigurationMap memory self, uint256 ltv) internal pure {
require(ltv <= MAX_VALID_LTV, Errors.RC_INVALID_LTV);
self.data = (self.data & LTV_MASK) | ltv;
}
/**
* @dev Gets the Loan to Value of the reserve
* @param self The reserve configuration
* @return The loan to value
**/
function getLtv(DataTypes.ReserveConfigurationMap storage self) internal view returns (uint256) {
return self.data & ~LTV_MASK;
}
/**
* @dev Sets the liquidation threshold of the reserve
* @param self The reserve configuration
* @param threshold The new liquidation threshold
**/
function setLiquidationThreshold(DataTypes.ReserveConfigurationMap memory self, uint256 threshold)
internal
pure
{
require(threshold <= MAX_VALID_LIQUIDATION_THRESHOLD, Errors.RC_INVALID_LIQ_THRESHOLD);
self.data =
(self.data & LIQUIDATION_THRESHOLD_MASK) |
(threshold << LIQUIDATION_THRESHOLD_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation threshold of the reserve
* @param self The reserve configuration
* @return The liquidation threshold
**/
function getLiquidationThreshold(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (uint256)
{
return (self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION;
}
/**
* @dev Sets the liquidation bonus of the reserve
* @param self The reserve configuration
* @param bonus The new liquidation bonus
**/
function setLiquidationBonus(DataTypes.ReserveConfigurationMap memory self, uint256 bonus)
internal
pure
{
require(bonus <= MAX_VALID_LIQUIDATION_BONUS, Errors.RC_INVALID_LIQ_BONUS);
self.data =
(self.data & LIQUIDATION_BONUS_MASK) |
(bonus << LIQUIDATION_BONUS_START_BIT_POSITION);
}
/**
* @dev Gets the liquidation bonus of the reserve
* @param self The reserve configuration
* @return The liquidation bonus
**/
function getLiquidationBonus(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (uint256)
{
return (self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION;
}
/**
* @dev Sets the decimals of the underlying asset of the reserve
* @param self The reserve configuration
* @param decimals The decimals
**/
function setDecimals(DataTypes.ReserveConfigurationMap memory self, uint256 decimals)
internal
pure
{
require(decimals <= MAX_VALID_DECIMALS, Errors.RC_INVALID_DECIMALS);
self.data = (self.data & DECIMALS_MASK) | (decimals << RESERVE_DECIMALS_START_BIT_POSITION);
}
/**
* @dev Gets the decimals of the underlying asset of the reserve
* @param self The reserve configuration
* @return The decimals of the asset
**/
function getDecimals(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (uint256)
{
return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;
}
/**
* @dev Sets the active state of the reserve
* @param self The reserve configuration
* @param active The active state
**/
function setActive(DataTypes.ReserveConfigurationMap memory self, bool active) internal pure {
self.data =
(self.data & ACTIVE_MASK) |
(uint256(active ? 1 : 0) << IS_ACTIVE_START_BIT_POSITION);
}
/**
* @dev Gets the active state of the reserve
* @param self The reserve configuration
* @return The active state
**/
function getActive(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~ACTIVE_MASK) != 0;
}
/**
* @dev Sets the frozen state of the reserve
* @param self The reserve configuration
* @param frozen The frozen state
**/
function setFrozen(DataTypes.ReserveConfigurationMap memory self, bool frozen) internal pure {
self.data =
(self.data & FROZEN_MASK) |
(uint256(frozen ? 1 : 0) << IS_FROZEN_START_BIT_POSITION);
}
/**
* @dev Gets the frozen state of the reserve
* @param self The reserve configuration
* @return The frozen state
**/
function getFrozen(DataTypes.ReserveConfigurationMap storage self) internal view returns (bool) {
return (self.data & ~FROZEN_MASK) != 0;
}
/**
* @dev Enables or disables borrowing on the reserve
* @param self The reserve configuration
* @param enabled True if the borrowing needs to be enabled, false otherwise
**/
function setBorrowingEnabled(DataTypes.ReserveConfigurationMap memory self, bool enabled)
internal
pure
{
self.data =
(self.data & BORROWING_MASK) |
(uint256(enabled ? 1 : 0) << BORROWING_ENABLED_START_BIT_POSITION);
}
/**
* @dev Gets the borrowing state of the reserve
* @param self The reserve configuration
* @return The borrowing state
**/
function getBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (bool)
{
return (self.data & ~BORROWING_MASK) != 0;
}
/**
* @dev Enables or disables stable rate borrowing on the reserve
* @param self The reserve configuration
* @param enabled True if the stable rate borrowing needs to be enabled, false otherwise
**/
function setStableRateBorrowingEnabled(
DataTypes.ReserveConfigurationMap memory self,
bool enabled
) internal pure {
self.data =
(self.data & STABLE_BORROWING_MASK) |
(uint256(enabled ? 1 : 0) << STABLE_BORROWING_ENABLED_START_BIT_POSITION);
}
/**
* @dev Gets the stable rate borrowing state of the reserve
* @param self The reserve configuration
* @return The stable rate borrowing state
**/
function getStableRateBorrowingEnabled(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (bool)
{
return (self.data & ~STABLE_BORROWING_MASK) != 0;
}
/**
* @dev Sets the reserve factor of the reserve
* @param self The reserve configuration
* @param reserveFactor The reserve factor
**/
function setReserveFactor(DataTypes.ReserveConfigurationMap memory self, uint256 reserveFactor)
internal
pure
{
require(reserveFactor <= MAX_VALID_RESERVE_FACTOR, Errors.RC_INVALID_RESERVE_FACTOR);
self.data =
(self.data & RESERVE_FACTOR_MASK) |
(reserveFactor << RESERVE_FACTOR_START_BIT_POSITION);
}
/**
* @dev Gets the reserve factor of the reserve
* @param self The reserve configuration
* @return The reserve factor
**/
function getReserveFactor(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (uint256)
{
return (self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION;
}
/**
* @dev Gets the configuration flags of the reserve
* @param self The reserve configuration
* @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
**/
function getFlags(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (
bool,
bool,
bool,
bool
)
{
uint256 dataLocal = self.data;
return (
(dataLocal & ~ACTIVE_MASK) != 0,
(dataLocal & ~FROZEN_MASK) != 0,
(dataLocal & ~BORROWING_MASK) != 0,
(dataLocal & ~STABLE_BORROWING_MASK) != 0
);
}
/**
* @dev Gets the configuration paramters of the reserve
* @param self The reserve configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
**/
function getParams(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
uint256 dataLocal = self.data;
return (
dataLocal & ~LTV_MASK,
(dataLocal & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(dataLocal & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
(dataLocal & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
(dataLocal & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
);
}
/**
* @dev Gets the configuration paramters of the reserve from a memory object
* @param self The reserve configuration
* @return The state params representing ltv, liquidation threshold, liquidation bonus, the reserve decimals
**/
function getParamsMemory(DataTypes.ReserveConfigurationMap memory self)
internal
pure
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return (
self.data & ~LTV_MASK,
(self.data & ~LIQUIDATION_THRESHOLD_MASK) >> LIQUIDATION_THRESHOLD_START_BIT_POSITION,
(self.data & ~LIQUIDATION_BONUS_MASK) >> LIQUIDATION_BONUS_START_BIT_POSITION,
(self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION,
(self.data & ~RESERVE_FACTOR_MASK) >> RESERVE_FACTOR_START_BIT_POSITION
);
}
/**
* @dev Gets the configuration flags of the reserve from a memory object
* @param self The reserve configuration
* @return The state flags representing active, frozen, borrowing enabled, stableRateBorrowing enabled
**/
function getFlagsMemory(DataTypes.ReserveConfigurationMap memory self)
internal
pure
returns (
bool,
bool,
bool,
bool
)
{
return (
(self.data & ~ACTIVE_MASK) != 0,
(self.data & ~FROZEN_MASK) != 0,
(self.data & ~BORROWING_MASK) != 0,
(self.data & ~STABLE_BORROWING_MASK) != 0
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Errors} from '../helpers/Errors.sol';
import {DataTypes} from '../types/DataTypes.sol';
/**
* @title UserConfiguration library
* @author Aave
* @notice Implements the bitmap logic to handle the user configuration
*/
library UserConfiguration {
uint256 internal constant BORROWING_MASK =
0x5555555555555555555555555555555555555555555555555555555555555555;
/**
* @dev Sets if the user is borrowing the reserve identified by reserveIndex
* @param self The configuration object
* @param reserveIndex The index of the reserve in the bitmap
* @param borrowing True if the user is borrowing the reserve, false otherwise
**/
function setBorrowing(
DataTypes.UserConfigurationMap storage self,
uint256 reserveIndex,
bool borrowing
) internal {
require(reserveIndex < 128, Errors.UL_INVALID_INDEX);
self.data =
(self.data & ~(1 << (reserveIndex * 2))) |
(uint256(borrowing ? 1 : 0) << (reserveIndex * 2));
}
/**
* @dev Sets if the user is using as collateral the reserve identified by reserveIndex
* @param self The configuration object
* @param reserveIndex The index of the reserve in the bitmap
* @param usingAsCollateral True if the user is usin the reserve as collateral, false otherwise
**/
function setUsingAsCollateral(
DataTypes.UserConfigurationMap storage self,
uint256 reserveIndex,
bool usingAsCollateral
) internal {
require(reserveIndex < 128, Errors.UL_INVALID_INDEX);
self.data =
(self.data & ~(1 << (reserveIndex * 2 + 1))) |
(uint256(usingAsCollateral ? 1 : 0) << (reserveIndex * 2 + 1));
}
/**
* @dev Used to validate if a user has been using the reserve for borrowing or as collateral
* @param self The configuration object
* @param reserveIndex The index of the reserve in the bitmap
* @return True if the user has been using a reserve for borrowing or as collateral, false otherwise
**/
function isUsingAsCollateralOrBorrowing(
DataTypes.UserConfigurationMap memory self,
uint256 reserveIndex
) internal pure returns (bool) {
require(reserveIndex < 128, Errors.UL_INVALID_INDEX);
return (self.data >> (reserveIndex * 2)) & 3 != 0;
}
/**
* @dev Used to validate if a user has been using the reserve for borrowing
* @param self The configuration object
* @param reserveIndex The index of the reserve in the bitmap
* @return True if the user has been using a reserve for borrowing, false otherwise
**/
function isBorrowing(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)
internal
pure
returns (bool)
{
require(reserveIndex < 128, Errors.UL_INVALID_INDEX);
return (self.data >> (reserveIndex * 2)) & 1 != 0;
}
/**
* @dev Used to validate if a user has been using the reserve as collateral
* @param self The configuration object
* @param reserveIndex The index of the reserve in the bitmap
* @return True if the user has been using a reserve as collateral, false otherwise
**/
function isUsingAsCollateral(DataTypes.UserConfigurationMap memory self, uint256 reserveIndex)
internal
pure
returns (bool)
{
require(reserveIndex < 128, Errors.UL_INVALID_INDEX);
return (self.data >> (reserveIndex * 2 + 1)) & 1 != 0;
}
/**
* @dev Used to validate if a user has been borrowing from any reserve
* @param self The configuration object
* @return True if the user has been borrowing any reserve, false otherwise
**/
function isBorrowingAny(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {
return self.data & BORROWING_MASK != 0;
}
/**
* @dev Used to validate if a user has not been using any reserve
* @param self The configuration object
* @return True if the user has been borrowing any reserve, false otherwise
**/
function isEmpty(DataTypes.UserConfigurationMap memory self) internal pure returns (bool) {
return self.data == 0;
}
}
// 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 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
returns (
uint256,
uint256,
uint256
);
function calculateInterestRates(
address reserve,
address aToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
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 {SafeMath} from '../../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {WadRayMath} from './WadRayMath.sol';
library MathUtils {
using SafeMath for uint256;
using WadRayMath for uint256;
/// @dev Ignoring leap years
uint256 internal constant SECONDS_PER_YEAR = 365 days;
/**
* @dev Function to calculate the interest accumulated using a linear interest rate formula
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate linearly accumulated during the timeDelta, in ray
**/
function calculateLinearInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
//solium-disable-next-line
uint256 timeDifference = block.timestamp.sub(uint256(lastUpdateTimestamp));
return (rate.mul(timeDifference) / SECONDS_PER_YEAR).add(WadRayMath.ray());
}
/**
* @dev Function to calculate the interest using a compounded interest rate formula
* To avoid expensive exponentiation, the calculation is performed using a binomial approximation:
*
* (1+x)^n = 1+n*x+[n/2*(n-1)]*x^2+[n/6*(n-1)*(n-2)*x^3...
*
* The approximation slightly underpays liquidity providers and undercharges borrowers, with the advantage of great gas cost reductions
* The whitepaper contains reference to the approximation and a table showing the margin of error per different time periods
*
* @param rate The interest rate, in ray
* @param lastUpdateTimestamp The timestamp of the last update of the interest
* @return The interest rate compounded during the timeDelta, in ray
**/
function calculateCompoundedInterest(
uint256 rate,
uint40 lastUpdateTimestamp,
uint256 currentTimestamp
) internal pure returns (uint256) {
//solium-disable-next-line
uint256 exp = currentTimestamp.sub(uint256(lastUpdateTimestamp));
if (exp == 0) {
return WadRayMath.ray();
}
uint256 expMinusOne = exp - 1;
uint256 expMinusTwo = exp > 2 ? exp - 2 : 0;
uint256 ratePerSecond = rate / SECONDS_PER_YEAR;
uint256 basePowerTwo = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
uint256 secondTerm = exp.mul(expMinusOne).mul(basePowerTwo) / 2;
uint256 thirdTerm = exp.mul(expMinusOne).mul(expMinusTwo).mul(basePowerThree) / 6;
return WadRayMath.ray().add(ratePerSecond.mul(exp)).add(secondTerm).add(thirdTerm);
}
/**
* @dev Calculates the compounded interest between the timestamp of the last update and the current block timestamp
* @param rate The interest rate (in ray)
* @param lastUpdateTimestamp The timestamp from which the interest accumulation needs to be calculated
**/
function calculateCompoundedInterest(uint256 rate, uint40 lastUpdateTimestamp)
internal
view
returns (uint256)
{
return calculateCompoundedInterest(rate, lastUpdateTimestamp, block.timestamp);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import {FlashLoanReceiverBase} from '../../flashloan/base/FlashLoanReceiverBase.sol';
import {MintableERC20} from '../tokens/MintableERC20.sol';
import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
contract MockFlashLoanReceiver is FlashLoanReceiverBase {
using SafeERC20 for IERC20;
ILendingPoolAddressesProvider internal _provider;
event ExecutedWithFail(address[] _assets, uint256[] _amounts, uint256[] _premiums);
event ExecutedWithSuccess(address[] _assets, uint256[] _amounts, uint256[] _premiums);
bool _failExecution;
uint256 _amountToApprove;
bool _simulateEOA;
constructor(ILendingPoolAddressesProvider provider) public FlashLoanReceiverBase(provider) {}
function setFailExecutionTransfer(bool fail) public {
_failExecution = fail;
}
function setAmountToApprove(uint256 amountToApprove) public {
_amountToApprove = amountToApprove;
}
function setSimulateEOA(bool flag) public {
_simulateEOA = flag;
}
function amountToApprove() public view returns (uint256) {
return _amountToApprove;
}
function simulateEOA() public view returns (bool) {
return _simulateEOA;
}
function executeOperation(
address[] memory assets,
uint256[] memory amounts,
uint256[] memory premiums,
address initiator,
bytes memory params
) public override returns (bool) {
params;
initiator;
if (_failExecution) {
emit ExecutedWithFail(assets, amounts, premiums);
return !_simulateEOA;
}
for (uint256 i = 0; i < assets.length; i++) {
//mint to this contract the specific amount
MintableERC20 token = MintableERC20(assets[i]);
//check the contract has the specified balance
require(
amounts[i] <= IERC20(assets[i]).balanceOf(address(this)),
'Invalid balance for the contract'
);
uint256 amountToReturn =
(_amountToApprove != 0) ? _amountToApprove : amounts[i].add(premiums[i]);
//execution does not fail - mint tokens and return them to the _destination
token.mint(premiums[i]);
IERC20(assets[i]).approve(address(LENDING_POOL), amountToReturn);
}
emit ExecutedWithSuccess(assets, amounts, premiums);
return true;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol';
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract MintableERC20 is ERC20 {
constructor(
string memory name,
string memory symbol,
uint8 decimals
) public ERC20(name, symbol) {
_setupDecimals(decimals);
}
/**
* @dev Function to mint tokens
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(uint256 value) public returns (bool) {
_mint(_msgSender(), value);
return true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import './Context.sol';
import './IERC20.sol';
import './SafeMath.sol';
import './Address.sol';
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'ERC20: transfer amount exceeds allowance')
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
'ERC20: decreased allowance below zero'
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), 'ERC20: transfer from the zero address');
require(recipient != address(0), 'ERC20: transfer to the zero address');
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, 'ERC20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: mint to the zero address');
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: burn from the zero address');
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, 'ERC20: burn amount exceeds balance');
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This 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 {}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {Address} from '../dependencies/openzeppelin/contracts/Address.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingPool} from '../interfaces/ILendingPool.sol';
import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
/**
* @title WalletBalanceProvider contract
* @author Aave, influenced by https://github.com/wbobeirne/eth-balance-checker/blob/master/contracts/BalanceChecker.sol
* @notice Implements a logic of getting multiple tokens balance for one user address
* @dev NOTE: THIS CONTRACT IS NOT USED WITHIN THE AAVE PROTOCOL. It's an accessory contract used to reduce the number of calls
* towards the blockchain from the Aave backend.
**/
contract WalletBalanceProvider {
using Address for address payable;
using Address for address;
using SafeERC20 for IERC20;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
address constant MOCK_ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/**
@dev Fallback function, don't accept any ETH
**/
receive() external payable {
//only contracts can send ETH to the core
require(msg.sender.isContract(), '22');
}
/**
@dev Check the token balance of a wallet in a token contract
Returns the balance of the token for user. Avoids possible errors:
- return 0 on non-contract address
**/
function balanceOf(address user, address token) public view returns (uint256) {
if (token == MOCK_ETH_ADDRESS) {
return user.balance; // ETH balance
// check if token is actually a contract
} else if (token.isContract()) {
return IERC20(token).balanceOf(user);
}
revert('INVALID_TOKEN');
}
/**
* @notice Fetches, for a list of _users and _tokens (ETH included with mock address), the balances
* @param users The list of users
* @param tokens The list of tokens
* @return And array with the concatenation of, for each user, his/her balances
**/
function batchBalanceOf(address[] calldata users, address[] calldata tokens)
external
view
returns (uint256[] memory)
{
uint256[] memory balances = new uint256[](users.length * tokens.length);
for (uint256 i = 0; i < users.length; i++) {
for (uint256 j = 0; j < tokens.length; j++) {
balances[i * tokens.length + j] = balanceOf(users[i], tokens[j]);
}
}
return balances;
}
/**
@dev provides balances of user wallet for all reserves available on the pool
*/
function getUserWalletBalances(address provider, address user)
external
view
returns (address[] memory, uint256[] memory)
{
ILendingPool pool = ILendingPool(ILendingPoolAddressesProvider(provider).getLendingPool());
address[] memory reserves = pool.getReservesList();
address[] memory reservesWithEth = new address[](reserves.length + 1);
for (uint256 i = 0; i < reserves.length; i++) {
reservesWithEth[i] = reserves[i];
}
reservesWithEth[reserves.length] = MOCK_ETH_ADDRESS;
uint256[] memory balances = new uint256[](reservesWithEth.length);
for (uint256 j = 0; j < reserves.length; j++) {
DataTypes.ReserveConfigurationMap memory configuration =
pool.getConfiguration(reservesWithEth[j]);
(bool isActive, , , ) = configuration.getFlagsMemory();
if (!isActive) {
balances[j] = 0;
continue;
}
balances[j] = balanceOf(user, reservesWithEth[j]);
}
balances[reserves.length] = balanceOf(user, MOCK_ETH_ADDRESS);
return (reservesWithEth, balances);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {IWETH} from './interfaces/IWETH.sol';
import {IWETHGateway} from './interfaces/IWETHGateway.sol';
import {ILendingPool} from '../interfaces/ILendingPool.sol';
import {IAToken} from '../interfaces/IAToken.sol';
import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol';
import {Helpers} from '../protocol/libraries/helpers/Helpers.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
contract WETHGateway is IWETHGateway, Ownable {
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
IWETH internal immutable WETH;
/**
* @dev Sets the WETH address and the LendingPoolAddressesProvider address. Infinite approves lending pool.
* @param weth Address of the Wrapped Ether contract
**/
constructor(address weth) public {
WETH = IWETH(weth);
}
function authorizeLendingPool(address lendingPool) external onlyOwner {
WETH.approve(lendingPool, uint256(-1));
}
/**
* @dev deposits WETH into the reserve, using native ETH. A corresponding amount of the overlying asset (aTokens)
* is minted.
* @param lendingPool address of the targeted underlying lending pool
* @param onBehalfOf address of the user who will receive the aTokens representing the deposit
* @param referralCode integrators are assigned a referral code and can potentially receive rewards.
**/
function depositETH(
address lendingPool,
address onBehalfOf,
uint16 referralCode
) external payable override {
WETH.deposit{value: msg.value}();
ILendingPool(lendingPool).deposit(address(WETH), msg.value, onBehalfOf, referralCode);
}
/**
* @dev withdraws the WETH _reserves of msg.sender.
* @param lendingPool address of the targeted underlying lending pool
* @param amount amount of aWETH to withdraw and receive native ETH
* @param to address of the user who will receive native ETH
*/
function withdrawETH(
address lendingPool,
uint256 amount,
address to
) external override {
IAToken aWETH = IAToken(ILendingPool(lendingPool).getReserveData(address(WETH)).aTokenAddress);
uint256 userBalance = aWETH.balanceOf(msg.sender);
uint256 amountToWithdraw = amount;
// if amount is equal to uint(-1), the user wants to redeem everything
if (amount == type(uint256).max) {
amountToWithdraw = userBalance;
}
aWETH.transferFrom(msg.sender, address(this), amountToWithdraw);
ILendingPool(lendingPool).withdraw(address(WETH), amountToWithdraw, address(this));
WETH.withdraw(amountToWithdraw);
_safeTransferETH(to, amountToWithdraw);
}
/**
* @dev repays a borrow on the WETH reserve, for the specified amount (or for the whole amount, if uint256(-1) is specified).
* @param lendingPool address of the targeted underlying lending pool
* @param amount the amount to repay, or uint256(-1) if the user wants to repay everything
* @param rateMode the rate mode to repay
* @param onBehalfOf the address for which msg.sender is repaying
*/
function repayETH(
address lendingPool,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external payable override {
(uint256 stableDebt, uint256 variableDebt) =
Helpers.getUserCurrentDebtMemory(
onBehalfOf,
ILendingPool(lendingPool).getReserveData(address(WETH))
);
uint256 paybackAmount =
DataTypes.InterestRateMode(rateMode) == DataTypes.InterestRateMode.STABLE
? stableDebt
: variableDebt;
if (amount < paybackAmount) {
paybackAmount = amount;
}
require(msg.value >= paybackAmount, 'msg.value is less than repayment amount');
WETH.deposit{value: paybackAmount}();
ILendingPool(lendingPool).repay(address(WETH), msg.value, rateMode, onBehalfOf);
// refund remaining dust eth
if (msg.value > paybackAmount) _safeTransferETH(msg.sender, msg.value - paybackAmount);
}
/**
* @dev borrow WETH, unwraps to ETH and send both the ETH and DebtTokens to msg.sender, via `approveDelegation` and onBehalf argument in `LendingPool.borrow`.
* @param lendingPool address of the targeted underlying lending pool
* @param amount the amount of ETH to borrow
* @param interesRateMode the interest rate mode
* @param referralCode integrators are assigned a referral code and can potentially receive rewards
*/
function borrowETH(
address lendingPool,
uint256 amount,
uint256 interesRateMode,
uint16 referralCode
) external override {
ILendingPool(lendingPool).borrow(
address(WETH),
amount,
interesRateMode,
referralCode,
msg.sender
);
WETH.withdraw(amount);
_safeTransferETH(msg.sender, amount);
}
/**
* @dev transfer ETH to an address, revert if it fails.
* @param to recipient of the transfer
* @param value the amount to send
*/
function _safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'ETH_TRANSFER_FAILED');
}
/**
* @dev transfer ERC20 from the utility contract, for ERC20 recovery in case of stuck tokens due
* direct transfers to the contract address.
* @param token token to transfer
* @param to recipient of the transfer
* @param amount amount to send
*/
function emergencyTokenTransfer(
address token,
address to,
uint256 amount
) external onlyOwner {
IERC20(token).transfer(to, amount);
}
/**
* @dev transfer native Ether from the utility contract, for native Ether recovery in case of stuck Ether
* due selfdestructs or transfer ether to pre-computated contract address before deployment.
* @param to recipient of the transfer
* @param amount amount to send
*/
function emergencyEtherTransfer(address to, uint256 amount) external onlyOwner {
_safeTransferETH(to, amount);
}
/**
* @dev Get WETH address used by WETHGateway
*/
function getWETHAddress() external view returns (address) {
return address(WETH);
}
/**
* @dev Only WETH contract is allowed to transfer ETH here. Prevent other addresses to send Ether to this contract.
*/
receive() external payable {
require(msg.sender == address(WETH), 'Receive not allowed');
}
/**
* @dev Revert fallback calls
*/
fallback() external payable {
revert('Fallback not allowed');
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function approve(address guy, uint256 wad) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 wad
) external returns (bool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IWETHGateway {
function depositETH(
address lendingPool,
address onBehalfOf,
uint16 referralCode
) external payable;
function withdrawETH(
address lendingPool,
uint256 amount,
address onBehalfOf
) external;
function repayETH(
address lendingPool,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external payable;
function borrowETH(
address lendingPool,
uint256 amount,
uint256 interesRateMode,
uint16 referralCode
) external;
}
// 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';
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import 'hardhat/console.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);
}
/**
* @dev Calculates the interest rates depending on the reserve's state and configurations
* @param reserve The address of the reserve
* @param liquidityAdded The liquidity added during the operation
* @param liquidityTaken The liquidity taken during the operation
* @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,
address aToken,
uint256 liquidityAdded,
uint256 liquidityTaken,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
override
returns (
uint256,
uint256,
uint256
)
{
uint256 availableLiquidity = IERC20(reserve).balanceOf(aToken);
//avoid stack too deep
availableLiquidity = availableLiquidity.add(liquidityAdded).sub(liquidityTaken);
return
calculateInterestRates(
reserve,
availableLiquidity,
totalStableDebt,
totalVariableDebt,
averageStableBorrowRate,
reserveFactor
);
}
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.
* NOTE This function is kept for compatibility with the previous DefaultInterestRateStrategy interface.
* New protocol implementation uses the new calculateInterestRates() interface
* @param reserve The address of the reserve
* @param availableLiquidity The liquidity available in the corresponding aToken
* @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
)
public
view
override
returns (
uint256,
uint256,
uint256
)
{
CalcInterestRatesLocalVars memory vars;
vars.totalDebt = totalStableDebt.add(totalVariableDebt);
vars.currentVariableBorrowRate = 0;
vars.currentStableBorrowRate = 0;
vars.currentLiquidityRate = 0;
vars.utilizationRate = vars.totalDebt == 0
? 0
: vars.totalDebt.rayDiv(availableLiquidity.add(vars.totalDebt));
vars.currentStableBorrowRate = ILendingRateOracle(addressesProvider.getLendingRateOracle())
.getMarketBorrowRate(reserve);
if (vars.utilizationRate > OPTIMAL_UTILIZATION_RATE) {
uint256 excessUtilizationRateRatio =
vars.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(vars.utilizationRate.rayDiv(OPTIMAL_UTILIZATION_RATE))
);
vars.currentVariableBorrowRate = _baseVariableBorrowRate.add(
vars.utilizationRate.rayMul(_variableRateSlope1).rayDiv(OPTIMAL_UTILIZATION_RATE)
);
}
vars.currentLiquidityRate = _getOverallBorrowRate(
totalStableDebt,
totalVariableDebt,
vars
.currentVariableBorrowRate,
averageStableBorrowRate
)
.rayMul(vars.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;
/**
* @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;
}
// 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: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {IUiPoolDataProvider} from './interfaces/IUiPoolDataProvider.sol';
import {ILendingPool} from '../interfaces/ILendingPool.sol';
import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol';
import {IAToken} from '../interfaces/IAToken.sol';
import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol';
import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol';
import {WadRayMath} from '../protocol/libraries/math/WadRayMath.sol';
import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
import {
DefaultReserveInterestRateStrategy
} from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol';
contract UiPoolDataProvider is IUiPoolDataProvider {
using WadRayMath for uint256;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
address public constant MOCK_USD_ADDRESS = 0x10F7Fc1F91Ba351f9C629c5947AD69bD03C05b96;
function getInterestRateStrategySlopes(DefaultReserveInterestRateStrategy interestRateStrategy)
internal
view
returns (
uint256,
uint256,
uint256,
uint256
)
{
return (
interestRateStrategy.variableRateSlope1(),
interestRateStrategy.variableRateSlope2(),
interestRateStrategy.stableRateSlope1(),
interestRateStrategy.stableRateSlope2()
);
}
function getReservesData(ILendingPoolAddressesProvider provider, address user)
external
view
override
returns (
AggregatedReserveData[] memory,
UserReserveData[] memory,
uint256
)
{
ILendingPool lendingPool = ILendingPool(provider.getLendingPool());
IPriceOracleGetter oracle = IPriceOracleGetter(provider.getPriceOracle());
address[] memory reserves = lendingPool.getReservesList();
DataTypes.UserConfigurationMap memory userConfig = lendingPool.getUserConfiguration(user);
AggregatedReserveData[] memory reservesData = new AggregatedReserveData[](reserves.length);
UserReserveData[] memory userReservesData =
new UserReserveData[](user != address(0) ? reserves.length : 0);
for (uint256 i = 0; i < reserves.length; i++) {
AggregatedReserveData memory reserveData = reservesData[i];
reserveData.underlyingAsset = reserves[i];
// reserve current state
DataTypes.ReserveData memory baseData =
lendingPool.getReserveData(reserveData.underlyingAsset);
reserveData.liquidityIndex = baseData.liquidityIndex;
reserveData.variableBorrowIndex = baseData.variableBorrowIndex;
reserveData.liquidityRate = baseData.currentLiquidityRate;
reserveData.variableBorrowRate = baseData.currentVariableBorrowRate;
reserveData.stableBorrowRate = baseData.currentStableBorrowRate;
reserveData.lastUpdateTimestamp = baseData.lastUpdateTimestamp;
reserveData.aTokenAddress = baseData.aTokenAddress;
reserveData.stableDebtTokenAddress = baseData.stableDebtTokenAddress;
reserveData.variableDebtTokenAddress = baseData.variableDebtTokenAddress;
reserveData.interestRateStrategyAddress = baseData.interestRateStrategyAddress;
reserveData.priceInEth = oracle.getAssetPrice(reserveData.underlyingAsset);
reserveData.availableLiquidity = IERC20Detailed(reserveData.underlyingAsset).balanceOf(
reserveData.aTokenAddress
);
(
reserveData.totalPrincipalStableDebt,
,
reserveData.averageStableRate,
reserveData.stableDebtLastUpdateTimestamp
) = IStableDebtToken(reserveData.stableDebtTokenAddress).getSupplyData();
reserveData.totalScaledVariableDebt = IVariableDebtToken(reserveData.variableDebtTokenAddress)
.scaledTotalSupply();
// reserve configuration
// we're getting this info from the aToken, because some of assets can be not compliant with ETC20Detailed
reserveData.symbol = IERC20Detailed(reserveData.aTokenAddress).symbol();
reserveData.name = '';
(
reserveData.baseLTVasCollateral,
reserveData.reserveLiquidationThreshold,
reserveData.reserveLiquidationBonus,
reserveData.decimals,
reserveData.reserveFactor
) = baseData.configuration.getParamsMemory();
(
reserveData.isActive,
reserveData.isFrozen,
reserveData.borrowingEnabled,
reserveData.stableBorrowRateEnabled
) = baseData.configuration.getFlagsMemory();
reserveData.usageAsCollateralEnabled = reserveData.baseLTVasCollateral != 0;
(
reserveData.variableRateSlope1,
reserveData.variableRateSlope2,
reserveData.stableRateSlope1,
reserveData.stableRateSlope2
) = getInterestRateStrategySlopes(
DefaultReserveInterestRateStrategy(reserveData.interestRateStrategyAddress)
);
if (user != address(0)) {
// user reserve data
userReservesData[i].underlyingAsset = reserveData.underlyingAsset;
userReservesData[i].scaledATokenBalance = IAToken(reserveData.aTokenAddress)
.scaledBalanceOf(user);
userReservesData[i].usageAsCollateralEnabledOnUser = userConfig.isUsingAsCollateral(i);
if (userConfig.isBorrowing(i)) {
userReservesData[i].scaledVariableDebt = IVariableDebtToken(
reserveData
.variableDebtTokenAddress
)
.scaledBalanceOf(user);
userReservesData[i].principalStableDebt = IStableDebtToken(
reserveData
.stableDebtTokenAddress
)
.principalBalanceOf(user);
if (userReservesData[i].principalStableDebt != 0) {
userReservesData[i].stableBorrowRate = IStableDebtToken(
reserveData
.stableDebtTokenAddress
)
.getUserStableRate(user);
userReservesData[i].stableBorrowLastUpdateTimestamp = IStableDebtToken(
reserveData
.stableDebtTokenAddress
)
.getUserLastUpdated(user);
}
}
}
}
return (reservesData, userReservesData, oracle.getAssetPrice(MOCK_USD_ADDRESS));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
interface IUiPoolDataProvider {
struct AggregatedReserveData {
address underlyingAsset;
string name;
string symbol;
uint256 decimals;
uint256 baseLTVasCollateral;
uint256 reserveLiquidationThreshold;
uint256 reserveLiquidationBonus;
uint256 reserveFactor;
bool usageAsCollateralEnabled;
bool borrowingEnabled;
bool stableBorrowRateEnabled;
bool isActive;
bool isFrozen;
// base data
uint128 liquidityIndex;
uint128 variableBorrowIndex;
uint128 liquidityRate;
uint128 variableBorrowRate;
uint128 stableBorrowRate;
uint40 lastUpdateTimestamp;
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
address interestRateStrategyAddress;
//
uint256 availableLiquidity;
uint256 totalPrincipalStableDebt;
uint256 averageStableRate;
uint256 stableDebtLastUpdateTimestamp;
uint256 totalScaledVariableDebt;
uint256 priceInEth;
uint256 variableRateSlope1;
uint256 variableRateSlope2;
uint256 stableRateSlope1;
uint256 stableRateSlope2;
}
//
// struct ReserveData {
// uint256 averageStableBorrowRate;
// uint256 totalLiquidity;
// }
struct UserReserveData {
address underlyingAsset;
uint256 scaledATokenBalance;
bool usageAsCollateralEnabledOnUser;
uint256 stableBorrowRate;
uint256 scaledVariableDebt;
uint256 principalStableDebt;
uint256 stableBorrowLastUpdateTimestamp;
}
//
// struct ATokenSupplyData {
// string name;
// string symbol;
// uint8 decimals;
// uint256 totalSupply;
// address aTokenAddress;
// }
function getReservesData(ILendingPoolAddressesProvider provider, address user)
external
view
returns (
AggregatedReserveData[] memory,
UserReserveData[] memory,
uint256
);
// function getUserReservesData(ILendingPoolAddressesProvider provider, address user)
// external
// view
// returns (UserReserveData[] memory);
//
// function getAllATokenSupply(ILendingPoolAddressesProvider provider)
// external
// view
// returns (ATokenSupplyData[] memory);
//
// function getATokenSupply(address[] calldata aTokens)
// external
// view
// returns (ATokenSupplyData[] memory);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {IERC20Detailed} from '../dependencies/openzeppelin/contracts/IERC20Detailed.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingPool} from '../interfaces/ILendingPool.sol';
import {IStableDebtToken} from '../interfaces/IStableDebtToken.sol';
import {IVariableDebtToken} from '../interfaces/IVariableDebtToken.sol';
import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../protocol/libraries/configuration/UserConfiguration.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
contract AaveProtocolDataProvider {
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
using UserConfiguration for DataTypes.UserConfigurationMap;
address constant MKR = 0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2;
address constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
struct TokenData {
string symbol;
address tokenAddress;
}
ILendingPoolAddressesProvider public immutable ADDRESSES_PROVIDER;
constructor(ILendingPoolAddressesProvider addressesProvider) public {
ADDRESSES_PROVIDER = addressesProvider;
}
function getAllReservesTokens() external view returns (TokenData[] memory) {
ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool());
address[] memory reserves = pool.getReservesList();
TokenData[] memory reservesTokens = new TokenData[](reserves.length);
for (uint256 i = 0; i < reserves.length; i++) {
if (reserves[i] == MKR) {
reservesTokens[i] = TokenData({symbol: 'MKR', tokenAddress: reserves[i]});
continue;
}
if (reserves[i] == ETH) {
reservesTokens[i] = TokenData({symbol: 'ETH', tokenAddress: reserves[i]});
continue;
}
reservesTokens[i] = TokenData({
symbol: IERC20Detailed(reserves[i]).symbol(),
tokenAddress: reserves[i]
});
}
return reservesTokens;
}
function getAllATokens() external view returns (TokenData[] memory) {
ILendingPool pool = ILendingPool(ADDRESSES_PROVIDER.getLendingPool());
address[] memory reserves = pool.getReservesList();
TokenData[] memory aTokens = new TokenData[](reserves.length);
for (uint256 i = 0; i < reserves.length; i++) {
DataTypes.ReserveData memory reserveData = pool.getReserveData(reserves[i]);
aTokens[i] = TokenData({
symbol: IERC20Detailed(reserveData.aTokenAddress).symbol(),
tokenAddress: reserveData.aTokenAddress
});
}
return aTokens;
}
function getReserveConfigurationData(address asset)
external
view
returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive,
bool isFrozen
)
{
DataTypes.ReserveConfigurationMap memory configuration =
ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getConfiguration(asset);
(ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor) = configuration
.getParamsMemory();
(isActive, isFrozen, borrowingEnabled, stableBorrowRateEnabled) = configuration
.getFlagsMemory();
usageAsCollateralEnabled = liquidationThreshold > 0;
}
function getReserveData(address asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
)
{
DataTypes.ReserveData memory reserve =
ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset);
return (
IERC20Detailed(asset).balanceOf(reserve.aTokenAddress),
IERC20Detailed(reserve.stableDebtTokenAddress).totalSupply(),
IERC20Detailed(reserve.variableDebtTokenAddress).totalSupply(),
reserve.currentLiquidityRate,
reserve.currentVariableBorrowRate,
reserve.currentStableBorrowRate,
IStableDebtToken(reserve.stableDebtTokenAddress).getAverageStableRate(),
reserve.liquidityIndex,
reserve.variableBorrowIndex,
reserve.lastUpdateTimestamp
);
}
function getUserReserveData(address asset, address user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
)
{
DataTypes.ReserveData memory reserve =
ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset);
DataTypes.UserConfigurationMap memory userConfig =
ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getUserConfiguration(user);
currentATokenBalance = IERC20Detailed(reserve.aTokenAddress).balanceOf(user);
currentVariableDebt = IERC20Detailed(reserve.variableDebtTokenAddress).balanceOf(user);
currentStableDebt = IERC20Detailed(reserve.stableDebtTokenAddress).balanceOf(user);
principalStableDebt = IStableDebtToken(reserve.stableDebtTokenAddress).principalBalanceOf(user);
scaledVariableDebt = IVariableDebtToken(reserve.variableDebtTokenAddress).scaledBalanceOf(user);
liquidityRate = reserve.currentLiquidityRate;
stableBorrowRate = IStableDebtToken(reserve.stableDebtTokenAddress).getUserStableRate(user);
stableRateLastUpdated = IStableDebtToken(reserve.stableDebtTokenAddress).getUserLastUpdated(
user
);
usageAsCollateralEnabled = userConfig.isUsingAsCollateral(reserve.id);
}
function getReserveTokensAddresses(address asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
)
{
DataTypes.ReserveData memory reserve =
ILendingPool(ADDRESSES_PROVIDER.getLendingPool()).getReserveData(asset);
return (
reserve.aTokenAddress,
reserve.stableDebtTokenAddress,
reserve.variableDebtTokenAddress
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {DebtTokenBase} from './base/DebtTokenBase.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
/**
* @title VariableDebtToken
* @notice Implements a variable debt token to track the borrowing positions of users
* at variable rate mode
* @author Aave
**/
contract VariableDebtToken is DebtTokenBase, IVariableDebtToken {
using WadRayMath for uint256;
uint256 public constant DEBT_TOKEN_REVISION = 0x1;
ILendingPool internal _pool;
address internal _underlyingAsset;
IAaveIncentivesController internal _incentivesController;
/**
* @dev Initializes the debt token.
* @param pool The address of the lending pool where this aToken will be used
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's
* @param debtTokenName The name of the token
* @param debtTokenSymbol The symbol of the token
*/
function initialize(
ILendingPool pool,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) public override initializer {
_setName(debtTokenName);
_setSymbol(debtTokenSymbol);
_setDecimals(debtTokenDecimals);
_pool = pool;
_underlyingAsset = underlyingAsset;
_incentivesController = incentivesController;
emit Initialized(
underlyingAsset,
address(pool),
address(incentivesController),
debtTokenDecimals,
debtTokenName,
debtTokenSymbol,
params
);
}
/**
* @dev Gets the revision of the stable debt token implementation
* @return The debt token implementation revision
**/
function getRevision() internal pure virtual override returns (uint256) {
return DEBT_TOKEN_REVISION;
}
/**
* @dev Calculates the accumulated debt balance of the user
* @return The debt balance of the user
**/
function balanceOf(address user) public view virtual override returns (uint256) {
uint256 scaledBalance = super.balanceOf(user);
if (scaledBalance == 0) {
return 0;
}
return scaledBalance.rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset));
}
/**
* @dev Mints debt token to the `onBehalfOf` address
* - Only callable by the LendingPool
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external override onlyLendingPool returns (bool) {
if (user != onBehalfOf) {
_decreaseBorrowAllowance(onBehalfOf, user, amount);
}
uint256 previousBalance = super.balanceOf(onBehalfOf);
uint256 amountScaled = amount.rayDiv(index);
require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT);
_mint(onBehalfOf, amountScaled);
emit Transfer(address(0), onBehalfOf, amount);
emit Mint(user, onBehalfOf, amount, index);
return previousBalance == 0;
}
/**
* @dev Burns user variable debt
* - Only callable by the LendingPool
* @param user The user whose debt is getting burned
* @param amount The amount getting burned
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external override onlyLendingPool {
uint256 amountScaled = amount.rayDiv(index);
require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT);
_burn(user, amountScaled);
emit Transfer(user, address(0), amount);
emit Burn(user, amount, index);
}
/**
* @dev Returns the principal debt balance of the user from
* @return The debt balance of the user since the last burn/mint action
**/
function scaledBalanceOf(address user) public view virtual override returns (uint256) {
return super.balanceOf(user);
}
/**
* @dev Returns the total supply of the variable debt token. Represents the total debt accrued by the users
* @return The total supply
**/
function totalSupply() public view virtual override returns (uint256) {
return super.totalSupply().rayMul(_pool.getReserveNormalizedVariableDebt(_underlyingAsset));
}
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return the scaled total supply
**/
function scaledTotalSupply() public view virtual override returns (uint256) {
return super.totalSupply();
}
/**
* @dev Returns the principal balance of the user and principal total supply.
* @param user The address of the user
* @return The principal balance of the user
* @return The principal total supply
**/
function getScaledUserBalanceAndSupply(address user)
external
view
override
returns (uint256, uint256)
{
return (super.balanceOf(user), super.totalSupply());
}
/**
* @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)
**/
function UNDERLYING_ASSET_ADDRESS() public view returns (address) {
return _underlyingAsset;
}
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view override returns (IAaveIncentivesController) {
return _getIncentivesController();
}
/**
* @dev Returns the address of the lending pool where this aToken is used
**/
function POOL() public view returns (ILendingPool) {
return _pool;
}
function _getIncentivesController() internal view override returns (IAaveIncentivesController) {
return _incentivesController;
}
function _getUnderlyingAssetAddress() internal view override returns (address) {
return _underlyingAsset;
}
function _getLendingPool() internal view override returns (ILendingPool) {
return _pool;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingPool} from '../../../interfaces/ILendingPool.sol';
import {ICreditDelegationToken} from '../../../interfaces/ICreditDelegationToken.sol';
import {
VersionedInitializable
} from '../../libraries/aave-upgradeability/VersionedInitializable.sol';
import {IncentivizedERC20} from '../IncentivizedERC20.sol';
import {Errors} from '../../libraries/helpers/Errors.sol';
/**
* @title DebtTokenBase
* @notice Base contract for different types of debt tokens, like StableDebtToken or VariableDebtToken
* @author Aave
*/
abstract contract DebtTokenBase is
IncentivizedERC20('DEBTTOKEN_IMPL', 'DEBTTOKEN_IMPL', 0),
VersionedInitializable,
ICreditDelegationToken
{
mapping(address => mapping(address => uint256)) internal _borrowAllowances;
/**
* @dev Only lending pool can call functions marked by this modifier
**/
modifier onlyLendingPool {
require(_msgSender() == address(_getLendingPool()), Errors.CT_CALLER_MUST_BE_LENDING_POOL);
_;
}
/**
* @dev delegates borrowing power to a user on the specific debt token
* @param delegatee the address receiving the delegated borrowing power
* @param amount the maximum amount being delegated. Delegation will still
* respect the liquidation constraints (even if delegated, a delegatee cannot
* force a delegator HF to go below 1)
**/
function approveDelegation(address delegatee, uint256 amount) external override {
_borrowAllowances[_msgSender()][delegatee] = amount;
emit BorrowAllowanceDelegated(_msgSender(), delegatee, _getUnderlyingAssetAddress(), amount);
}
/**
* @dev returns the borrow allowance of the user
* @param fromUser The user to giving allowance
* @param toUser The user to give allowance to
* @return the current allowance of toUser
**/
function borrowAllowance(address fromUser, address toUser)
external
view
override
returns (uint256)
{
return _borrowAllowances[fromUser][toUser];
}
/**
* @dev Being non transferrable, the debt token does not implement any of the
* standard ERC20 functions for transfer and allowance.
**/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
recipient;
amount;
revert('TRANSFER_NOT_SUPPORTED');
}
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
owner;
spender;
revert('ALLOWANCE_NOT_SUPPORTED');
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
spender;
amount;
revert('APPROVAL_NOT_SUPPORTED');
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
sender;
recipient;
amount;
revert('TRANSFER_NOT_SUPPORTED');
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
override
returns (bool)
{
spender;
addedValue;
revert('ALLOWANCE_NOT_SUPPORTED');
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
override
returns (bool)
{
spender;
subtractedValue;
revert('ALLOWANCE_NOT_SUPPORTED');
}
function _decreaseBorrowAllowance(
address delegator,
address delegatee,
uint256 amount
) internal {
uint256 newAllowance =
_borrowAllowances[delegator][delegatee].sub(amount, Errors.BORROW_ALLOWANCE_NOT_ENOUGH);
_borrowAllowances[delegator][delegatee] = newAllowance;
emit BorrowAllowanceDelegated(delegator, delegatee, _getUnderlyingAssetAddress(), newAllowance);
}
function _getUnderlyingAssetAddress() internal view virtual returns (address);
function _getLendingPool() internal view virtual returns (ILendingPool);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface ICreditDelegationToken {
event BorrowAllowanceDelegated(
address indexed fromUser,
address indexed toUser,
address asset,
uint256 amount
);
/**
* @dev delegates borrowing power to a user on the specific debt token
* @param delegatee the address receiving the delegated borrowing power
* @param amount the maximum amount being delegated. Delegation will still
* respect the liquidation constraints (even if delegated, a delegatee cannot
* force a delegator HF to go below 1)
**/
function approveDelegation(address delegatee, uint256 amount) external;
/**
* @dev returns the borrow allowance of the user
* @param fromUser The user to giving allowance
* @param toUser The user to give allowance to
* @return the current allowance of toUser
**/
function borrowAllowance(address fromUser, address toUser) external view returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Context} from '../../dependencies/openzeppelin/contracts/Context.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol';
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
/**
* @title ERC20
* @notice Basic ERC20 implementation
* @author Aave, inspired by the Openzeppelin ERC20 implementation
**/
abstract contract IncentivizedERC20 is Context, IERC20, IERC20Detailed {
using SafeMath for uint256;
mapping(address => uint256) internal _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 internal _totalSupply;
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 override returns (string memory) {
return _name;
}
/**
* @return The symbol of the token
**/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @return The decimals of the token
**/
function decimals() public view override returns (uint8) {
return _decimals;
}
/**
* @return The total supply of the token
**/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @return The balance of the token
**/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @return Abstract function implemented by the child aToken/debtToken.
* Done this way in order to not break compatibility with previous versions of aTokens/debtTokens
**/
function _getIncentivesController() internal view virtual returns(IAaveIncentivesController);
/**
* @dev Executes a transfer of tokens from _msgSender() to recipient
* @param recipient The recipient of the tokens
* @param amount The amount of tokens being transferred
* @return `true` if the transfer succeeds, `false` otherwise
**/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
emit Transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev Returns the allowance of spender on the tokens owned by owner
* @param owner The owner of the tokens
* @param spender The user allowed to spend the owner's tokens
* @return The amount of owner's tokens spender is allowed to spend
**/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev Allows `spender` to spend the tokens owned by _msgSender()
* @param spender The user allowed to spend _msgSender() tokens
* @return `true`
**/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev Executes a transfer of token from sender to recipient, if _msgSender() is allowed to do so
* @param sender The owner of the tokens
* @param recipient The recipient of the tokens
* @param amount The amount of tokens being transferred
* @return `true` if the transfer succeeds, `false` otherwise
**/
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')
);
emit Transfer(sender, recipient, amount);
return true;
}
/**
* @dev Increases the allowance of spender to spend _msgSender() tokens
* @param spender The user allowed to spend on behalf of _msgSender()
* @param addedValue The amount being added to the allowance
* @return `true`
**/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Decreases the allowance of spender to spend _msgSender() tokens
* @param spender The user allowed to spend on behalf of _msgSender()
* @param subtractedValue The amount being subtracted to the allowance
* @return `true`
**/
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;
}
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 oldSenderBalance = _balances[sender];
_balances[sender] = oldSenderBalance.sub(amount, 'ERC20: transfer amount exceeds balance');
uint256 oldRecipientBalance = _balances[recipient];
_balances[recipient] = _balances[recipient].add(amount);
if (address(_getIncentivesController()) != address(0)) {
uint256 currentTotalSupply = _totalSupply;
_getIncentivesController().handleAction(sender, currentTotalSupply, oldSenderBalance);
if (sender != recipient) {
_getIncentivesController().handleAction(recipient, currentTotalSupply, oldRecipientBalance);
}
}
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: mint to the zero address');
_beforeTokenTransfer(address(0), account, amount);
uint256 oldTotalSupply = _totalSupply;
_totalSupply = oldTotalSupply.add(amount);
uint256 oldAccountBalance = _balances[account];
_balances[account] = oldAccountBalance.add(amount);
if (address(_getIncentivesController()) != address(0)) {
_getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance);
}
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), 'ERC20: burn from the zero address');
_beforeTokenTransfer(account, address(0), amount);
uint256 oldTotalSupply = _totalSupply;
_totalSupply = oldTotalSupply.sub(amount);
uint256 oldAccountBalance = _balances[account];
_balances[account] = oldAccountBalance.sub(amount, 'ERC20: burn amount exceeds balance');
if (address(_getIncentivesController()) != address(0)) {
_getIncentivesController().handleAction(account, oldTotalSupply, oldAccountBalance);
}
}
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), 'ERC20: approve from the zero address');
require(spender != address(0), 'ERC20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _setName(string memory newName) internal {
_name = newName;
}
function _setSymbol(string memory newSymbol) internal {
_symbol = newSymbol;
}
function _setDecimals(uint8 newDecimals) internal {
_decimals = newDecimals;
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {VariableDebtToken} from '../../protocol/tokenization/VariableDebtToken.sol';
contract MockVariableDebtToken is VariableDebtToken {
function getRevision() internal pure override returns (uint256) {
return 0x2;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {AToken} from '../../protocol/tokenization/AToken.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
contract MockAToken is AToken {
function getRevision() internal pure override returns (uint256) {
return 0x2;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IAToken} from '../../interfaces/IAToken.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol';
import {IncentivizedERC20} from './IncentivizedERC20.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
/**
* @title Aave ERC20 AToken
* @dev Implementation of the interest bearing token for the Aave protocol
* @author Aave
*/
contract AToken is
VersionedInitializable,
IncentivizedERC20('ATOKEN_IMPL', 'ATOKEN_IMPL', 0),
IAToken
{
using WadRayMath for uint256;
using SafeERC20 for IERC20;
bytes public constant EIP712_REVISION = bytes('1');
bytes32 internal constant EIP712_DOMAIN =
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)');
bytes32 public constant PERMIT_TYPEHASH =
keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)');
uint256 public constant ATOKEN_REVISION = 0x1;
/// @dev owner => next valid nonce to submit with permit()
mapping(address => uint256) public _nonces;
bytes32 public DOMAIN_SEPARATOR;
ILendingPool internal _pool;
address internal _treasury;
address internal _underlyingAsset;
IAaveIncentivesController internal _incentivesController;
modifier onlyLendingPool {
require(_msgSender() == address(_pool), Errors.CT_CALLER_MUST_BE_LENDING_POOL);
_;
}
function getRevision() internal pure virtual override returns (uint256) {
return ATOKEN_REVISION;
}
/**
* @dev Initializes the aToken
* @param pool The address of the lending pool where this aToken will be used
* @param treasury The address of the Aave treasury, receiving the fees on this aToken
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param aTokenDecimals The decimals of the aToken, same as the underlying asset's
* @param aTokenName The name of the aToken
* @param aTokenSymbol The symbol of the aToken
*/
function initialize(
ILendingPool pool,
address treasury,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 aTokenDecimals,
string calldata aTokenName,
string calldata aTokenSymbol,
bytes calldata params
) external override initializer {
uint256 chainId;
//solium-disable-next-line
assembly {
chainId := chainid()
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
EIP712_DOMAIN,
keccak256(bytes(aTokenName)),
keccak256(EIP712_REVISION),
chainId,
address(this)
)
);
_setName(aTokenName);
_setSymbol(aTokenSymbol);
_setDecimals(aTokenDecimals);
_pool = pool;
_treasury = treasury;
_underlyingAsset = underlyingAsset;
_incentivesController = incentivesController;
emit Initialized(
underlyingAsset,
address(pool),
treasury,
address(incentivesController),
aTokenDecimals,
aTokenName,
aTokenSymbol,
params
);
}
/**
* @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* - Only callable by the LendingPool, as extra state updates there need to be managed
* @param user The owner of the aTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external override onlyLendingPool {
uint256 amountScaled = amount.rayDiv(index);
require(amountScaled != 0, Errors.CT_INVALID_BURN_AMOUNT);
_burn(user, amountScaled);
IERC20(_underlyingAsset).safeTransfer(receiverOfUnderlying, amount);
emit Transfer(user, address(0), amount);
emit Burn(user, receiverOfUnderlying, amount, index);
}
/**
* @dev Mints `amount` aTokens to `user`
* - Only callable by the LendingPool, as extra state updates there need to be managed
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external override onlyLendingPool returns (bool) {
uint256 previousBalance = super.balanceOf(user);
uint256 amountScaled = amount.rayDiv(index);
require(amountScaled != 0, Errors.CT_INVALID_MINT_AMOUNT);
_mint(user, amountScaled);
emit Transfer(address(0), user, amount);
emit Mint(user, amount, index);
return previousBalance == 0;
}
/**
* @dev Mints aTokens to the reserve treasury
* - Only callable by the LendingPool
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external override onlyLendingPool {
if (amount == 0) {
return;
}
address treasury = _treasury;
// Compared to the normal mint, we don't check for rounding errors.
// The amount to mint can easily be very small since it is a fraction of the interest ccrued.
// In that case, the treasury will experience a (very small) loss, but it
// wont cause potentially valid transactions to fail.
_mint(treasury, amount.rayDiv(index));
emit Transfer(address(0), treasury, amount);
emit Mint(treasury, amount, index);
}
/**
* @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* - Only callable by the LendingPool
* @param from The address getting liquidated, current owner of the aTokens
* @param to The recipient
* @param value The amount of tokens getting transferred
**/
function transferOnLiquidation(
address from,
address to,
uint256 value
) external override onlyLendingPool {
// Being a normal transfer, the Transfer() and BalanceTransfer() are emitted
// so no need to emit a specific event here
_transfer(from, to, value, false);
emit Transfer(from, to, value);
}
/**
* @dev Calculates the balance of the user: principal balance + interest generated by the principal
* @param user The user whose balance is calculated
* @return The balance of the user
**/
function balanceOf(address user)
public
view
override(IncentivizedERC20, IERC20)
returns (uint256)
{
return super.balanceOf(user).rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset));
}
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view override returns (uint256) {
return super.balanceOf(user);
}
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user)
external
view
override
returns (uint256, uint256)
{
return (super.balanceOf(user), super.totalSupply());
}
/**
* @dev calculates the total supply of the specific aToken
* since the balance of every single user increases over time, the total supply
* does that too.
* @return the current total supply
**/
function totalSupply() public view override(IncentivizedERC20, IERC20) returns (uint256) {
uint256 currentSupplyScaled = super.totalSupply();
if (currentSupplyScaled == 0) {
return 0;
}
return currentSupplyScaled.rayMul(_pool.getReserveNormalizedIncome(_underlyingAsset));
}
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return the scaled total supply
**/
function scaledTotalSupply() public view virtual override returns (uint256) {
return super.totalSupply();
}
/**
* @dev Returns the address of the Aave treasury, receiving the fees on this aToken
**/
function RESERVE_TREASURY_ADDRESS() public view returns (address) {
return _treasury;
}
/**
* @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)
**/
function UNDERLYING_ASSET_ADDRESS() public view returns (address) {
return _underlyingAsset;
}
/**
* @dev Returns the address of the lending pool where this aToken is used
**/
function POOL() public view returns (ILendingPool) {
return _pool;
}
/**
* @dev For internal usage in the logic of the parent contract IncentivizedERC20
**/
function _getIncentivesController() internal view override returns (IAaveIncentivesController) {
return _incentivesController;
}
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view override returns (IAaveIncentivesController) {
return _getIncentivesController();
}
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param target The recipient of the aTokens
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address target, uint256 amount)
external
override
onlyLendingPool
returns (uint256)
{
IERC20(_underlyingAsset).safeTransfer(target, amount);
return amount;
}
/**
* @dev Invoked to execute actions on the aToken side after a repayment.
* @param user The user executing the repayment
* @param amount The amount getting repaid
**/
function handleRepayment(address user, uint256 amount) external override onlyLendingPool {}
/**
* @dev implements the permit function as for
* https://github.com/ethereum/EIPs/blob/8a34d644aacf0f9f8f00815307fd7dd5da07655f/EIPS/eip-2612.md
* @param owner The owner of the funds
* @param spender The spender
* @param value The amount
* @param deadline The deadline timestamp, type(uint256).max for max deadline
* @param v Signature param
* @param s Signature param
* @param r Signature param
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner != address(0), 'INVALID_OWNER');
//solium-disable-next-line
require(block.timestamp <= deadline, 'INVALID_EXPIRATION');
uint256 currentValidNonce = _nonces[owner];
bytes32 digest =
keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, currentValidNonce, deadline))
)
);
require(owner == ecrecover(digest, v, r, s), 'INVALID_SIGNATURE');
_nonces[owner] = currentValidNonce.add(1);
_approve(owner, spender, value);
}
/**
* @dev Transfers the aTokens between two users. Validates the transfer
* (ie checks for valid HF after the transfer) if required
* @param from The source address
* @param to The destination address
* @param amount The amount getting transferred
* @param validate `true` if the transfer needs to be validated
**/
function _transfer(
address from,
address to,
uint256 amount,
bool validate
) internal {
address underlyingAsset = _underlyingAsset;
ILendingPool pool = _pool;
uint256 index = pool.getReserveNormalizedIncome(underlyingAsset);
uint256 fromBalanceBefore = super.balanceOf(from).rayMul(index);
uint256 toBalanceBefore = super.balanceOf(to).rayMul(index);
super._transfer(from, to, amount.rayDiv(index));
if (validate) {
pool.finalizeTransfer(underlyingAsset, from, to, amount, fromBalanceBefore, toBalanceBefore);
}
emit BalanceTransfer(from, to, amount, index);
}
/**
* @dev Overrides the parent _transfer to force validated transfer() and transferFrom()
* @param from The source address
* @param to The destination address
* @param amount The amount getting transferred
**/
function _transfer(
address from,
address to,
uint256 amount
) internal override {
_transfer(from, to, amount, true);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IDelegationToken} from '../../interfaces/IDelegationToken.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {AToken} from './AToken.sol';
/**
* @title Aave AToken enabled to delegate voting power of the underlying asset to a different address
* @dev The underlying asset needs to be compatible with the COMP delegation interface
* @author Aave
*/
contract DelegationAwareAToken is AToken {
modifier onlyPoolAdmin {
require(
_msgSender() == ILendingPool(_pool).getAddressesProvider().getPoolAdmin(),
Errors.CALLER_NOT_POOL_ADMIN
);
_;
}
/**
* @dev Delegates voting power of the underlying asset to a `delegatee` address
* @param delegatee The address that will receive the delegation
**/
function delegateUnderlyingTo(address delegatee) external onlyPoolAdmin {
IDelegationToken(_underlyingAsset).delegate(delegatee);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title IDelegationToken
* @dev Implements an interface for tokens with delegation COMP/UNI compatible
* @author Aave
**/
interface IDelegationToken {
function delegate(address delegatee) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol';
import {
ILendingPoolAddressesProviderRegistry
} from '../../interfaces/ILendingPoolAddressesProviderRegistry.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
/**
* @title LendingPoolAddressesProviderRegistry contract
* @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets
* - Used for indexing purposes of Aave protocol's markets
* - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with,
* for example with `0` for the Aave main market and `1` for the next created
* @author Aave
**/
contract LendingPoolAddressesProviderRegistry is Ownable, ILendingPoolAddressesProviderRegistry {
mapping(address => uint256) private _addressesProviders;
address[] private _addressesProvidersList;
/**
* @dev Returns the list of registered addresses provider
* @return The list of addresses provider, potentially containing address(0) elements
**/
function getAddressesProvidersList() external view override returns (address[] memory) {
address[] memory addressesProvidersList = _addressesProvidersList;
uint256 maxLength = addressesProvidersList.length;
address[] memory activeProviders = new address[](maxLength);
for (uint256 i = 0; i < maxLength; i++) {
if (_addressesProviders[addressesProvidersList[i]] > 0) {
activeProviders[i] = addressesProvidersList[i];
}
}
return activeProviders;
}
/**
* @dev Registers an addresses provider
* @param provider The address of the new LendingPoolAddressesProvider
* @param id The id for the new LendingPoolAddressesProvider, referring to the market it belongs to
**/
function registerAddressesProvider(address provider, uint256 id) external override onlyOwner {
require(id != 0, Errors.LPAPR_INVALID_ADDRESSES_PROVIDER_ID);
_addressesProviders[provider] = id;
_addToAddressesProvidersList(provider);
emit AddressesProviderRegistered(provider);
}
/**
* @dev Removes a LendingPoolAddressesProvider from the list of registered addresses provider
* @param provider The LendingPoolAddressesProvider address
**/
function unregisterAddressesProvider(address provider) external override onlyOwner {
require(_addressesProviders[provider] > 0, Errors.LPAPR_PROVIDER_NOT_REGISTERED);
_addressesProviders[provider] = 0;
emit AddressesProviderUnregistered(provider);
}
/**
* @dev Returns the id on a registered LendingPoolAddressesProvider
* @return The id or 0 if the LendingPoolAddressesProvider is not registered
*/
function getAddressesProviderIdByAddress(address addressesProvider)
external
view
override
returns (uint256)
{
return _addressesProviders[addressesProvider];
}
function _addToAddressesProvidersList(address provider) internal {
uint256 providersCount = _addressesProvidersList.length;
for (uint256 i = 0; i < providersCount; i++) {
if (_addressesProvidersList[i] == provider) {
return;
}
}
_addressesProvidersList.push(provider);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
/**
* @title LendingPoolAddressesProviderRegistry contract
* @dev Main registry of LendingPoolAddressesProvider of multiple Aave protocol's markets
* - Used for indexing purposes of Aave protocol's markets
* - The id assigned to a LendingPoolAddressesProvider refers to the market it is connected with,
* for example with `0` for the Aave main market and `1` for the next created
* @author Aave
**/
interface ILendingPoolAddressesProviderRegistry {
event AddressesProviderRegistered(address indexed newAddress);
event AddressesProviderUnregistered(address indexed newAddress);
function getAddressesProvidersList() external view returns (address[] memory);
function getAddressesProviderIdByAddress(address addressesProvider)
external
view
returns (uint256);
function registerAddressesProvider(address provider, uint256 id) external;
function unregisterAddressesProvider(address provider) external;
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol';
import {IChainlinkAggregator} from '../interfaces/IChainlinkAggregator.sol';
import {SafeERC20} from '../dependencies/openzeppelin/contracts/SafeERC20.sol';
/// @title AaveOracle
/// @author Aave
/// @notice Proxy smart contract to get the price of an asset from a price source, with Chainlink Aggregator
/// smart contracts as primary option
/// - If the returned price by a Chainlink aggregator is <= 0, the call is forwarded to a fallbackOracle
/// - Owned by the Aave governance system, allowed to add sources for assets, replace them
/// and change the fallbackOracle
contract AaveOracle is IPriceOracleGetter, Ownable {
using SafeERC20 for IERC20;
event WethSet(address indexed weth);
event AssetSourceUpdated(address indexed asset, address indexed source);
event FallbackOracleUpdated(address indexed fallbackOracle);
mapping(address => IChainlinkAggregator) private assetsSources;
IPriceOracleGetter private _fallbackOracle;
address public immutable WETH;
/// @notice Constructor
/// @param assets The addresses of the assets
/// @param sources The address of the source of each asset
/// @param fallbackOracle The address of the fallback oracle to use if the data of an
/// aggregator is not consistent
constructor(
address[] memory assets,
address[] memory sources,
address fallbackOracle,
address weth
) public {
_setFallbackOracle(fallbackOracle);
_setAssetsSources(assets, sources);
WETH = weth;
emit WethSet(weth);
}
/// @notice External function called by the Aave governance to set or replace sources of assets
/// @param assets The addresses of the assets
/// @param sources The address of the source of each asset
function setAssetSources(address[] calldata assets, address[] calldata sources)
external
onlyOwner
{
_setAssetsSources(assets, sources);
}
/// @notice Sets the fallbackOracle
/// - Callable only by the Aave governance
/// @param fallbackOracle The address of the fallbackOracle
function setFallbackOracle(address fallbackOracle) external onlyOwner {
_setFallbackOracle(fallbackOracle);
}
/// @notice Internal function to set the sources for each asset
/// @param assets The addresses of the assets
/// @param sources The address of the source of each asset
function _setAssetsSources(address[] memory assets, address[] memory sources) internal {
require(assets.length == sources.length, 'INCONSISTENT_PARAMS_LENGTH');
for (uint256 i = 0; i < assets.length; i++) {
assetsSources[assets[i]] = IChainlinkAggregator(sources[i]);
emit AssetSourceUpdated(assets[i], sources[i]);
}
}
/// @notice Internal function to set the fallbackOracle
/// @param fallbackOracle The address of the fallbackOracle
function _setFallbackOracle(address fallbackOracle) internal {
_fallbackOracle = IPriceOracleGetter(fallbackOracle);
emit FallbackOracleUpdated(fallbackOracle);
}
/// @notice Gets an asset price by address
/// @param asset The asset address
function getAssetPrice(address asset) public view override returns (uint256) {
IChainlinkAggregator source = assetsSources[asset];
if (asset == WETH) {
return 1 ether;
} else if (address(source) == address(0)) {
return _fallbackOracle.getAssetPrice(asset);
} else {
int256 price = IChainlinkAggregator(source).latestAnswer();
if (price > 0) {
return uint256(price);
} else {
return _fallbackOracle.getAssetPrice(asset);
}
}
}
/// @notice Gets a list of prices from a list of assets addresses
/// @param assets The list of assets addresses
function getAssetsPrices(address[] calldata assets) external view returns (uint256[] memory) {
uint256[] memory prices = new uint256[](assets.length);
for (uint256 i = 0; i < assets.length; i++) {
prices[i] = getAssetPrice(assets[i]);
}
return prices;
}
/// @notice Gets the address of the source for an asset address
/// @param asset The address of the asset
/// @return address The address of the source
function getSourceOfAsset(address asset) external view returns (address) {
return address(assetsSources[asset]);
}
/// @notice Gets the address of the fallback oracle
/// @return address The addres of the fallback oracle
function getFallbackOracle() external view returns (address) {
return address(_fallbackOracle);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
interface IChainlinkAggregator {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
event NewRound(uint256 indexed roundId, address indexed startedBy);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol';
import {
InitializableImmutableAdminUpgradeabilityProxy
} from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol';
import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IERC20Detailed} from '../../dependencies/openzeppelin/contracts/IERC20Detailed.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {PercentageMath} from '../libraries/math/PercentageMath.sol';
import {DataTypes} from '../libraries/types/DataTypes.sol';
import {IInitializableDebtToken} from '../../interfaces/IInitializableDebtToken.sol';
import {IInitializableAToken} from '../../interfaces/IInitializableAToken.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
import {ILendingPoolConfigurator} from '../../interfaces/ILendingPoolConfigurator.sol';
/**
* @title LendingPoolConfigurator contract
* @author Aave
* @dev Implements the configuration methods for the Aave protocol
**/
contract LendingPoolConfigurator is VersionedInitializable, ILendingPoolConfigurator {
using SafeMath for uint256;
using PercentageMath for uint256;
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
ILendingPoolAddressesProvider internal addressesProvider;
ILendingPool internal pool;
modifier onlyPoolAdmin {
require(addressesProvider.getPoolAdmin() == msg.sender, Errors.CALLER_NOT_POOL_ADMIN);
_;
}
modifier onlyEmergencyAdmin {
require(
addressesProvider.getEmergencyAdmin() == msg.sender,
Errors.LPC_CALLER_NOT_EMERGENCY_ADMIN
);
_;
}
uint256 internal constant CONFIGURATOR_REVISION = 0x1;
function getRevision() internal pure override returns (uint256) {
return CONFIGURATOR_REVISION;
}
function initialize(ILendingPoolAddressesProvider provider) public initializer {
addressesProvider = provider;
pool = ILendingPool(addressesProvider.getLendingPool());
}
/**
* @dev Initializes reserves in batch
**/
function batchInitReserve(InitReserveInput[] calldata input) external onlyPoolAdmin {
ILendingPool cachedPool = pool;
for (uint256 i = 0; i < input.length; i++) {
_initReserve(cachedPool, input[i]);
}
}
function _initReserve(ILendingPool pool, InitReserveInput calldata input) internal {
address aTokenProxyAddress =
_initTokenWithProxy(
input.aTokenImpl,
abi.encodeWithSelector(
IInitializableAToken.initialize.selector,
pool,
input.treasury,
input.underlyingAsset,
IAaveIncentivesController(input.incentivesController),
input.underlyingAssetDecimals,
input.aTokenName,
input.aTokenSymbol,
input.params
)
);
address stableDebtTokenProxyAddress =
_initTokenWithProxy(
input.stableDebtTokenImpl,
abi.encodeWithSelector(
IInitializableDebtToken.initialize.selector,
pool,
input.underlyingAsset,
IAaveIncentivesController(input.incentivesController),
input.underlyingAssetDecimals,
input.stableDebtTokenName,
input.stableDebtTokenSymbol,
input.params
)
);
address variableDebtTokenProxyAddress =
_initTokenWithProxy(
input.variableDebtTokenImpl,
abi.encodeWithSelector(
IInitializableDebtToken.initialize.selector,
pool,
input.underlyingAsset,
IAaveIncentivesController(input.incentivesController),
input.underlyingAssetDecimals,
input.variableDebtTokenName,
input.variableDebtTokenSymbol,
input.params
)
);
pool.initReserve(
input.underlyingAsset,
aTokenProxyAddress,
stableDebtTokenProxyAddress,
variableDebtTokenProxyAddress,
input.interestRateStrategyAddress
);
DataTypes.ReserveConfigurationMap memory currentConfig =
pool.getConfiguration(input.underlyingAsset);
currentConfig.setDecimals(input.underlyingAssetDecimals);
currentConfig.setActive(true);
currentConfig.setFrozen(false);
pool.setConfiguration(input.underlyingAsset, currentConfig.data);
emit ReserveInitialized(
input.underlyingAsset,
aTokenProxyAddress,
stableDebtTokenProxyAddress,
variableDebtTokenProxyAddress,
input.interestRateStrategyAddress
);
}
/**
* @dev Updates the aToken implementation for the reserve
**/
function updateAToken(UpdateATokenInput calldata input) external onlyPoolAdmin {
ILendingPool cachedPool = pool;
DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset);
(, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory();
bytes memory encodedCall = abi.encodeWithSelector(
IInitializableAToken.initialize.selector,
cachedPool,
input.treasury,
input.asset,
input.incentivesController,
decimals,
input.name,
input.symbol,
input.params
);
_upgradeTokenImplementation(
reserveData.aTokenAddress,
input.implementation,
encodedCall
);
emit ATokenUpgraded(input.asset, reserveData.aTokenAddress, input.implementation);
}
/**
* @dev Updates the stable debt token implementation for the reserve
**/
function updateStableDebtToken(UpdateDebtTokenInput calldata input) external onlyPoolAdmin {
ILendingPool cachedPool = pool;
DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset);
(, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory();
bytes memory encodedCall = abi.encodeWithSelector(
IInitializableDebtToken.initialize.selector,
cachedPool,
input.asset,
input.incentivesController,
decimals,
input.name,
input.symbol,
input.params
);
_upgradeTokenImplementation(
reserveData.stableDebtTokenAddress,
input.implementation,
encodedCall
);
emit StableDebtTokenUpgraded(
input.asset,
reserveData.stableDebtTokenAddress,
input.implementation
);
}
/**
* @dev Updates the variable debt token implementation for the asset
**/
function updateVariableDebtToken(UpdateDebtTokenInput calldata input)
external
onlyPoolAdmin
{
ILendingPool cachedPool = pool;
DataTypes.ReserveData memory reserveData = cachedPool.getReserveData(input.asset);
(, , , uint256 decimals, ) = cachedPool.getConfiguration(input.asset).getParamsMemory();
bytes memory encodedCall = abi.encodeWithSelector(
IInitializableDebtToken.initialize.selector,
cachedPool,
input.asset,
input.incentivesController,
decimals,
input.name,
input.symbol,
input.params
);
_upgradeTokenImplementation(
reserveData.variableDebtTokenAddress,
input.implementation,
encodedCall
);
emit VariableDebtTokenUpgraded(
input.asset,
reserveData.variableDebtTokenAddress,
input.implementation
);
}
/**
* @dev Enables borrowing on a reserve
* @param asset The address of the underlying asset of the reserve
* @param stableBorrowRateEnabled True if stable borrow rate needs to be enabled by default on this reserve
**/
function enableBorrowingOnReserve(address asset, bool stableBorrowRateEnabled)
external
onlyPoolAdmin
{
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setBorrowingEnabled(true);
currentConfig.setStableRateBorrowingEnabled(stableBorrowRateEnabled);
pool.setConfiguration(asset, currentConfig.data);
emit BorrowingEnabledOnReserve(asset, stableBorrowRateEnabled);
}
/**
* @dev Disables borrowing on a reserve
* @param asset The address of the underlying asset of the reserve
**/
function disableBorrowingOnReserve(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setBorrowingEnabled(false);
pool.setConfiguration(asset, currentConfig.data);
emit BorrowingDisabledOnReserve(asset);
}
/**
* @dev Configures the reserve collateralization parameters
* all the values are expressed in percentages with two decimals of precision. A valid value is 10000, which means 100.00%
* @param asset The address of the underlying asset of the reserve
* @param ltv The loan to value of the asset when used as collateral
* @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized
* @param liquidationBonus The bonus liquidators receive to liquidate this asset. The values is always above 100%. A value of 105%
* means the liquidator will receive a 5% bonus
**/
function configureReserveAsCollateral(
address asset,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus
) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
//validation of the parameters: the LTV can
//only be lower or equal than the liquidation threshold
//(otherwise a loan against the asset would cause instantaneous liquidation)
require(ltv <= liquidationThreshold, Errors.LPC_INVALID_CONFIGURATION);
if (liquidationThreshold != 0) {
//liquidation bonus must be bigger than 100.00%, otherwise the liquidator would receive less
//collateral than needed to cover the debt
require(
liquidationBonus > PercentageMath.PERCENTAGE_FACTOR,
Errors.LPC_INVALID_CONFIGURATION
);
//if threshold * bonus is less than PERCENTAGE_FACTOR, it's guaranteed that at the moment
//a loan is taken there is enough collateral available to cover the liquidation bonus
require(
liquidationThreshold.percentMul(liquidationBonus) <= PercentageMath.PERCENTAGE_FACTOR,
Errors.LPC_INVALID_CONFIGURATION
);
} else {
require(liquidationBonus == 0, Errors.LPC_INVALID_CONFIGURATION);
//if the liquidation threshold is being set to 0,
// the reserve is being disabled as collateral. To do so,
//we need to ensure no liquidity is deposited
_checkNoLiquidity(asset);
}
currentConfig.setLtv(ltv);
currentConfig.setLiquidationThreshold(liquidationThreshold);
currentConfig.setLiquidationBonus(liquidationBonus);
pool.setConfiguration(asset, currentConfig.data);
emit CollateralConfigurationChanged(asset, ltv, liquidationThreshold, liquidationBonus);
}
/**
* @dev Enable stable rate borrowing on a reserve
* @param asset The address of the underlying asset of the reserve
**/
function enableReserveStableRate(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setStableRateBorrowingEnabled(true);
pool.setConfiguration(asset, currentConfig.data);
emit StableRateEnabledOnReserve(asset);
}
/**
* @dev Disable stable rate borrowing on a reserve
* @param asset The address of the underlying asset of the reserve
**/
function disableReserveStableRate(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setStableRateBorrowingEnabled(false);
pool.setConfiguration(asset, currentConfig.data);
emit StableRateDisabledOnReserve(asset);
}
/**
* @dev Activates a reserve
* @param asset The address of the underlying asset of the reserve
**/
function activateReserve(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setActive(true);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveActivated(asset);
}
/**
* @dev Deactivates a reserve
* @param asset The address of the underlying asset of the reserve
**/
function deactivateReserve(address asset) external onlyPoolAdmin {
_checkNoLiquidity(asset);
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setActive(false);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveDeactivated(asset);
}
/**
* @dev Freezes a reserve. A frozen reserve doesn't allow any new deposit, borrow or rate swap
* but allows repayments, liquidations, rate rebalances and withdrawals
* @param asset The address of the underlying asset of the reserve
**/
function freezeReserve(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setFrozen(true);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveFrozen(asset);
}
/**
* @dev Unfreezes a reserve
* @param asset The address of the underlying asset of the reserve
**/
function unfreezeReserve(address asset) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setFrozen(false);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveUnfrozen(asset);
}
/**
* @dev Updates the reserve factor of a reserve
* @param asset The address of the underlying asset of the reserve
* @param reserveFactor The new reserve factor of the reserve
**/
function setReserveFactor(address asset, uint256 reserveFactor) external onlyPoolAdmin {
DataTypes.ReserveConfigurationMap memory currentConfig = pool.getConfiguration(asset);
currentConfig.setReserveFactor(reserveFactor);
pool.setConfiguration(asset, currentConfig.data);
emit ReserveFactorChanged(asset, reserveFactor);
}
/**
* @dev Sets the interest rate strategy of a reserve
* @param asset The address of the underlying asset of the reserve
* @param rateStrategyAddress The new address of the interest strategy contract
**/
function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress)
external
onlyPoolAdmin
{
pool.setReserveInterestRateStrategyAddress(asset, rateStrategyAddress);
emit ReserveInterestRateStrategyChanged(asset, rateStrategyAddress);
}
/**
* @dev pauses or unpauses all the actions of the protocol, including aToken transfers
* @param val true if protocol needs to be paused, false otherwise
**/
function setPoolPause(bool val) external onlyEmergencyAdmin {
pool.setPause(val);
}
function _initTokenWithProxy(address implementation, bytes memory initParams)
internal
returns (address)
{
InitializableImmutableAdminUpgradeabilityProxy proxy =
new InitializableImmutableAdminUpgradeabilityProxy(address(this));
proxy.initialize(implementation, initParams);
return address(proxy);
}
function _upgradeTokenImplementation(
address proxyAddress,
address implementation,
bytes memory initParams
) internal {
InitializableImmutableAdminUpgradeabilityProxy proxy =
InitializableImmutableAdminUpgradeabilityProxy(payable(proxyAddress));
proxy.upgradeToAndCall(implementation, initParams);
}
function _checkNoLiquidity(address asset) internal view {
DataTypes.ReserveData memory reserveData = pool.getReserveData(asset);
uint256 availableLiquidity = IERC20Detailed(asset).balanceOf(reserveData.aTokenAddress);
require(
availableLiquidity == 0 && reserveData.currentLiquidityRate == 0,
Errors.LPC_RESERVE_LIQUIDITY_NOT_0
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './BaseImmutableAdminUpgradeabilityProxy.sol';
import '../../../dependencies/openzeppelin/upgradeability/InitializableUpgradeabilityProxy.sol';
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends BaseAdminUpgradeabilityProxy with an initializer function
*/
contract InitializableImmutableAdminUpgradeabilityProxy is
BaseImmutableAdminUpgradeabilityProxy,
InitializableUpgradeabilityProxy
{
constructor(address admin) public BaseImmutableAdminUpgradeabilityProxy(admin) {}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override(BaseImmutableAdminUpgradeabilityProxy, Proxy) {
BaseImmutableAdminUpgradeabilityProxy._willFallback();
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface ILendingPoolConfigurator {
struct InitReserveInput {
address aTokenImpl;
address stableDebtTokenImpl;
address variableDebtTokenImpl;
uint8 underlyingAssetDecimals;
address interestRateStrategyAddress;
address underlyingAsset;
address treasury;
address incentivesController;
string underlyingAssetName;
string aTokenName;
string aTokenSymbol;
string variableDebtTokenName;
string variableDebtTokenSymbol;
string stableDebtTokenName;
string stableDebtTokenSymbol;
bytes params;
}
struct UpdateATokenInput {
address asset;
address treasury;
address incentivesController;
string name;
string symbol;
address implementation;
bytes params;
}
struct UpdateDebtTokenInput {
address asset;
address incentivesController;
string name;
string symbol;
address implementation;
bytes params;
}
/**
* @dev Emitted when a reserve is initialized.
* @param asset The address of the underlying asset of the reserve
* @param aToken The address of the associated aToken contract
* @param stableDebtToken The address of the associated stable rate debt token
* @param variableDebtToken The address of the associated variable rate debt token
* @param interestRateStrategyAddress The address of the interest rate strategy for the reserve
**/
event ReserveInitialized(
address indexed asset,
address indexed aToken,
address stableDebtToken,
address variableDebtToken,
address interestRateStrategyAddress
);
/**
* @dev Emitted when borrowing is enabled on a reserve
* @param asset The address of the underlying asset of the reserve
* @param stableRateEnabled True if stable rate borrowing is enabled, false otherwise
**/
event BorrowingEnabledOnReserve(address indexed asset, bool stableRateEnabled);
/**
* @dev Emitted when borrowing is disabled on a reserve
* @param asset The address of the underlying asset of the reserve
**/
event BorrowingDisabledOnReserve(address indexed asset);
/**
* @dev Emitted when the collateralization risk parameters for the specified asset are updated.
* @param asset The address of the underlying asset of the reserve
* @param ltv The loan to value of the asset when used as collateral
* @param liquidationThreshold The threshold at which loans using this asset as collateral will be considered undercollateralized
* @param liquidationBonus The bonus liquidators receive to liquidate this asset
**/
event CollateralConfigurationChanged(
address indexed asset,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus
);
/**
* @dev Emitted when stable rate borrowing is enabled on a reserve
* @param asset The address of the underlying asset of the reserve
**/
event StableRateEnabledOnReserve(address indexed asset);
/**
* @dev Emitted when stable rate borrowing is disabled on a reserve
* @param asset The address of the underlying asset of the reserve
**/
event StableRateDisabledOnReserve(address indexed asset);
/**
* @dev Emitted when a reserve is activated
* @param asset The address of the underlying asset of the reserve
**/
event ReserveActivated(address indexed asset);
/**
* @dev Emitted when a reserve is deactivated
* @param asset The address of the underlying asset of the reserve
**/
event ReserveDeactivated(address indexed asset);
/**
* @dev Emitted when a reserve is frozen
* @param asset The address of the underlying asset of the reserve
**/
event ReserveFrozen(address indexed asset);
/**
* @dev Emitted when a reserve is unfrozen
* @param asset The address of the underlying asset of the reserve
**/
event ReserveUnfrozen(address indexed asset);
/**
* @dev Emitted when a reserve factor is updated
* @param asset The address of the underlying asset of the reserve
* @param factor The new reserve factor
**/
event ReserveFactorChanged(address indexed asset, uint256 factor);
/**
* @dev Emitted when the reserve decimals are updated
* @param asset The address of the underlying asset of the reserve
* @param decimals The new decimals
**/
event ReserveDecimalsChanged(address indexed asset, uint256 decimals);
/**
* @dev Emitted when a reserve interest strategy contract is updated
* @param asset The address of the underlying asset of the reserve
* @param strategy The new address of the interest strategy contract
**/
event ReserveInterestRateStrategyChanged(address indexed asset, address strategy);
/**
* @dev Emitted when an aToken implementation is upgraded
* @param asset The address of the underlying asset of the reserve
* @param proxy The aToken proxy address
* @param implementation The new aToken implementation
**/
event ATokenUpgraded(
address indexed asset,
address indexed proxy,
address indexed implementation
);
/**
* @dev Emitted when the implementation of a stable debt token is upgraded
* @param asset The address of the underlying asset of the reserve
* @param proxy The stable debt token proxy address
* @param implementation The new aToken implementation
**/
event StableDebtTokenUpgraded(
address indexed asset,
address indexed proxy,
address indexed implementation
);
/**
* @dev Emitted when the implementation of a variable debt token is upgraded
* @param asset The address of the underlying asset of the reserve
* @param proxy The variable debt token proxy address
* @param implementation The new aToken implementation
**/
event VariableDebtTokenUpgraded(
address indexed asset,
address indexed proxy,
address indexed implementation
);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import '../../../dependencies/openzeppelin/upgradeability/BaseUpgradeabilityProxy.sol';
/**
* @title BaseImmutableAdminUpgradeabilityProxy
* @author Aave, inspired by the OpenZeppelin upgradeability proxy pattern
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks. The admin role is stored in an immutable, which
* helps saving transactions costs
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseImmutableAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
address immutable ADMIN;
constructor(address admin) public {
ADMIN = admin;
}
modifier ifAdmin() {
if (msg.sender == ADMIN) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return ADMIN;
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal virtual override {
require(msg.sender != ADMIN, 'Cannot call fallback function from the proxy admin');
super._willFallback();
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './BaseUpgradeabilityProxy.sol';
/**
* @title InitializableUpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with an initializer for initializing
* implementation and init data.
*/
contract InitializableUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract initializer.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(address _logic, bytes memory _data) public payable {
require(_implementation() == address(0));
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './Proxy.sol';
import '../contracts/Address.sol';
/**
* @title BaseUpgradeabilityProxy
* @dev This contract implements a proxy that allows to change the
* implementation address to which it will delegate.
* Such a change is called an implementation upgrade.
*/
contract BaseUpgradeabilityProxy is Proxy {
/**
* @dev Emitted when the implementation is upgraded.
* @param implementation Address of the new implementation.
*/
event Upgraded(address indexed implementation);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation.
* @return impl Address of the current implementation
*/
function _implementation() internal view override returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
impl := sload(slot)
}
}
/**
* @dev Upgrades the proxy to a new implementation.
* @param newImplementation Address of the new implementation.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation address of the proxy.
* @param newImplementation Address of the new implementation.
*/
function _setImplementation(address newImplementation) internal {
require(
Address.isContract(newImplementation),
'Cannot set a proxy implementation to a non-contract address'
);
bytes32 slot = IMPLEMENTATION_SLOT;
//solium-disable-next-line
assembly {
sstore(slot, newImplementation)
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity ^0.6.0;
/**
* @title Proxy
* @dev Implements delegation of calls to other contracts, with proper
* forwarding of return values and bubbling of failures.
* It defines a fallback function that delegates all calls to the address
* returned by the abstract _implementation() internal function.
*/
abstract contract Proxy {
/**
* @dev Fallback function.
* Implemented entirely in `_fallback`.
*/
fallback() external payable {
_fallback();
}
/**
* @return The Address of the implementation.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates execution to an implementation contract.
* This is a low level function that doesn't return to its internal call site.
* It will return to the external caller whatever the implementation returns.
* @param implementation Address to delegate.
*/
function _delegate(address implementation) internal {
//solium-disable-next-line
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev Function that is run as the first thing in the fallback function.
* Can be redefined in derived contracts to add functionality.
* Redefinitions must call super._willFallback().
*/
function _willFallback() internal virtual {}
/**
* @dev fallback implementation.
* Extracted to enable manual triggering.
*/
function _fallback() internal {
_willFallback();
_delegate(_implementation());
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {DebtTokenBase} from './base/DebtTokenBase.sol';
import {MathUtils} from '../libraries/math/MathUtils.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {IAaveIncentivesController} from '../../interfaces/IAaveIncentivesController.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
/**
* @title StableDebtToken
* @notice Implements a stable debt token to track the borrowing positions of users
* at stable rate mode
* @author Aave
**/
contract StableDebtToken is IStableDebtToken, DebtTokenBase {
using WadRayMath for uint256;
uint256 public constant DEBT_TOKEN_REVISION = 0x1;
uint256 internal _avgStableRate;
mapping(address => uint40) internal _timestamps;
mapping(address => uint256) internal _usersStableRate;
uint40 internal _totalSupplyTimestamp;
ILendingPool internal _pool;
address internal _underlyingAsset;
IAaveIncentivesController internal _incentivesController;
/**
* @dev Initializes the debt token.
* @param pool The address of the lending pool where this aToken will be used
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param debtTokenDecimals The decimals of the debtToken, same as the underlying asset's
* @param debtTokenName The name of the token
* @param debtTokenSymbol The symbol of the token
*/
function initialize(
ILendingPool pool,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 debtTokenDecimals,
string memory debtTokenName,
string memory debtTokenSymbol,
bytes calldata params
) public override initializer {
_setName(debtTokenName);
_setSymbol(debtTokenSymbol);
_setDecimals(debtTokenDecimals);
_pool = pool;
_underlyingAsset = underlyingAsset;
_incentivesController = incentivesController;
emit Initialized(
underlyingAsset,
address(pool),
address(incentivesController),
debtTokenDecimals,
debtTokenName,
debtTokenSymbol,
params
);
}
/**
* @dev Gets the revision of the stable debt token implementation
* @return The debt token implementation revision
**/
function getRevision() internal pure virtual override returns (uint256) {
return DEBT_TOKEN_REVISION;
}
/**
* @dev Returns the average stable rate across all the stable rate debt
* @return the average stable rate
**/
function getAverageStableRate() external view virtual override returns (uint256) {
return _avgStableRate;
}
/**
* @dev Returns the timestamp of the last user action
* @return The last update timestamp
**/
function getUserLastUpdated(address user) external view virtual override returns (uint40) {
return _timestamps[user];
}
/**
* @dev Returns the stable rate of the user
* @param user The address of the user
* @return The stable rate of user
**/
function getUserStableRate(address user) external view virtual override returns (uint256) {
return _usersStableRate[user];
}
/**
* @dev Calculates the current user debt balance
* @return The accumulated debt of the user
**/
function balanceOf(address account) public view virtual override returns (uint256) {
uint256 accountBalance = super.balanceOf(account);
uint256 stableRate = _usersStableRate[account];
if (accountBalance == 0) {
return 0;
}
uint256 cumulatedInterest =
MathUtils.calculateCompoundedInterest(stableRate, _timestamps[account]);
return accountBalance.rayMul(cumulatedInterest);
}
struct MintLocalVars {
uint256 previousSupply;
uint256 nextSupply;
uint256 amountInRay;
uint256 newStableRate;
uint256 currentAvgStableRate;
}
/**
* @dev Mints debt token to the `onBehalfOf` address.
* - Only callable by the LendingPool
* - The resulting rate is the weighted average between the rate of the new debt
* and the rate of the previous debt
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt tokens to mint
* @param rate The rate of the debt being minted
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 rate
) external override onlyLendingPool returns (bool) {
MintLocalVars memory vars;
if (user != onBehalfOf) {
_decreaseBorrowAllowance(onBehalfOf, user, amount);
}
(, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(onBehalfOf);
vars.previousSupply = totalSupply();
vars.currentAvgStableRate = _avgStableRate;
vars.nextSupply = _totalSupply = vars.previousSupply.add(amount);
vars.amountInRay = amount.wadToRay();
vars.newStableRate = _usersStableRate[onBehalfOf]
.rayMul(currentBalance.wadToRay())
.add(vars.amountInRay.rayMul(rate))
.rayDiv(currentBalance.add(amount).wadToRay());
require(vars.newStableRate <= type(uint128).max, Errors.SDT_STABLE_DEBT_OVERFLOW);
_usersStableRate[onBehalfOf] = vars.newStableRate;
//solium-disable-next-line
_totalSupplyTimestamp = _timestamps[onBehalfOf] = uint40(block.timestamp);
// Calculates the updated average stable rate
vars.currentAvgStableRate = _avgStableRate = vars
.currentAvgStableRate
.rayMul(vars.previousSupply.wadToRay())
.add(rate.rayMul(vars.amountInRay))
.rayDiv(vars.nextSupply.wadToRay());
_mint(onBehalfOf, amount.add(balanceIncrease), vars.previousSupply);
emit Transfer(address(0), onBehalfOf, amount);
emit Mint(
user,
onBehalfOf,
amount,
currentBalance,
balanceIncrease,
vars.newStableRate,
vars.currentAvgStableRate,
vars.nextSupply
);
return currentBalance == 0;
}
/**
* @dev Burns debt of `user`
* @param user The address of the user getting his debt burned
* @param amount The amount of debt tokens getting burned
**/
function burn(address user, uint256 amount) external override onlyLendingPool {
(, uint256 currentBalance, uint256 balanceIncrease) = _calculateBalanceIncrease(user);
uint256 previousSupply = totalSupply();
uint256 newAvgStableRate = 0;
uint256 nextSupply = 0;
uint256 userStableRate = _usersStableRate[user];
// Since the total supply and each single user debt accrue separately,
// there might be accumulation errors so that the last borrower repaying
// mght actually try to repay more than the available debt supply.
// In this case we simply set the total supply and the avg stable rate to 0
if (previousSupply <= amount) {
_avgStableRate = 0;
_totalSupply = 0;
} else {
nextSupply = _totalSupply = previousSupply.sub(amount);
uint256 firstTerm = _avgStableRate.rayMul(previousSupply.wadToRay());
uint256 secondTerm = userStableRate.rayMul(amount.wadToRay());
// For the same reason described above, when the last user is repaying it might
// happen that user rate * user balance > avg rate * total supply. In that case,
// we simply set the avg rate to 0
if (secondTerm >= firstTerm) {
newAvgStableRate = _avgStableRate = _totalSupply = 0;
} else {
newAvgStableRate = _avgStableRate = firstTerm.sub(secondTerm).rayDiv(nextSupply.wadToRay());
}
}
if (amount == currentBalance) {
_usersStableRate[user] = 0;
_timestamps[user] = 0;
} else {
//solium-disable-next-line
_timestamps[user] = uint40(block.timestamp);
}
//solium-disable-next-line
_totalSupplyTimestamp = uint40(block.timestamp);
if (balanceIncrease > amount) {
uint256 amountToMint = balanceIncrease.sub(amount);
_mint(user, amountToMint, previousSupply);
emit Mint(
user,
user,
amountToMint,
currentBalance,
balanceIncrease,
userStableRate,
newAvgStableRate,
nextSupply
);
} else {
uint256 amountToBurn = amount.sub(balanceIncrease);
_burn(user, amountToBurn, previousSupply);
emit Burn(user, amountToBurn, currentBalance, balanceIncrease, newAvgStableRate, nextSupply);
}
emit Transfer(user, address(0), amount);
}
/**
* @dev Calculates the increase in balance since the last user interaction
* @param user The address of the user for which the interest is being accumulated
* @return The previous principal balance, the new principal balance and the balance increase
**/
function _calculateBalanceIncrease(address user)
internal
view
returns (
uint256,
uint256,
uint256
)
{
uint256 previousPrincipalBalance = super.balanceOf(user);
if (previousPrincipalBalance == 0) {
return (0, 0, 0);
}
// Calculation of the accrued interest since the last accumulation
uint256 balanceIncrease = balanceOf(user).sub(previousPrincipalBalance);
return (
previousPrincipalBalance,
previousPrincipalBalance.add(balanceIncrease),
balanceIncrease
);
}
/**
* @dev Returns the principal and total supply, the average borrow rate and the last supply update timestamp
**/
function getSupplyData()
public
view
override
returns (
uint256,
uint256,
uint256,
uint40
)
{
uint256 avgRate = _avgStableRate;
return (super.totalSupply(), _calcTotalSupply(avgRate), avgRate, _totalSupplyTimestamp);
}
/**
* @dev Returns the the total supply and the average stable rate
**/
function getTotalSupplyAndAvgRate() public view override returns (uint256, uint256) {
uint256 avgRate = _avgStableRate;
return (_calcTotalSupply(avgRate), avgRate);
}
/**
* @dev Returns the total supply
**/
function totalSupply() public view override returns (uint256) {
return _calcTotalSupply(_avgStableRate);
}
/**
* @dev Returns the timestamp at which the total supply was updated
**/
function getTotalSupplyLastUpdated() public view override returns (uint40) {
return _totalSupplyTimestamp;
}
/**
* @dev Returns the principal debt balance of the user from
* @param user The user's address
* @return The debt balance of the user since the last burn/mint action
**/
function principalBalanceOf(address user) external view virtual override returns (uint256) {
return super.balanceOf(user);
}
/**
* @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)
**/
function UNDERLYING_ASSET_ADDRESS() public view returns (address) {
return _underlyingAsset;
}
/**
* @dev Returns the address of the lending pool where this aToken is used
**/
function POOL() public view returns (ILendingPool) {
return _pool;
}
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController() external view override returns (IAaveIncentivesController) {
return _getIncentivesController();
}
/**
* @dev For internal usage in the logic of the parent contracts
**/
function _getIncentivesController() internal view override returns (IAaveIncentivesController) {
return _incentivesController;
}
/**
* @dev For internal usage in the logic of the parent contracts
**/
function _getUnderlyingAssetAddress() internal view override returns (address) {
return _underlyingAsset;
}
/**
* @dev For internal usage in the logic of the parent contracts
**/
function _getLendingPool() internal view override returns (ILendingPool) {
return _pool;
}
/**
* @dev Calculates the total supply
* @param avgRate The average rate at which the total supply increases
* @return The debt balance of the user since the last burn/mint action
**/
function _calcTotalSupply(uint256 avgRate) internal view virtual returns (uint256) {
uint256 principalSupply = super.totalSupply();
if (principalSupply == 0) {
return 0;
}
uint256 cumulatedInterest =
MathUtils.calculateCompoundedInterest(avgRate, _totalSupplyTimestamp);
return principalSupply.rayMul(cumulatedInterest);
}
/**
* @dev Mints stable debt tokens to an user
* @param account The account receiving the debt tokens
* @param amount The amount being minted
* @param oldTotalSupply the total supply before the minting event
**/
function _mint(
address account,
uint256 amount,
uint256 oldTotalSupply
) internal {
uint256 oldAccountBalance = _balances[account];
_balances[account] = oldAccountBalance.add(amount);
if (address(_incentivesController) != address(0)) {
_incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance);
}
}
/**
* @dev Burns stable debt tokens of an user
* @param account The user getting his debt burned
* @param amount The amount being burned
* @param oldTotalSupply The total supply before the burning event
**/
function _burn(
address account,
uint256 amount,
uint256 oldTotalSupply
) internal {
uint256 oldAccountBalance = _balances[account];
_balances[account] = oldAccountBalance.sub(amount, Errors.SDT_BURN_EXCEEDS_BALANCE);
if (address(_incentivesController) != address(0)) {
_incentivesController.handleAction(account, oldTotalSupply, oldAccountBalance);
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {StableDebtToken} from '../../protocol/tokenization/StableDebtToken.sol';
contract MockStableDebtToken is StableDebtToken {
function getRevision() internal pure override returns (uint256) {
return 0x2;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {SafeMath} from '../../dependencies/openzeppelin/contracts/SafeMath.sol';
import {IERC20} from '../../dependencies/openzeppelin/contracts/IERC20.sol';
import {SafeERC20} from '../../dependencies/openzeppelin/contracts/SafeERC20.sol';
import {Address} from '../../dependencies/openzeppelin/contracts/Address.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
import {IAToken} from '../../interfaces/IAToken.sol';
import {IVariableDebtToken} from '../../interfaces/IVariableDebtToken.sol';
import {IFlashLoanReceiver} from '../../flashloan/interfaces/IFlashLoanReceiver.sol';
import {IPriceOracleGetter} from '../../interfaces/IPriceOracleGetter.sol';
import {IStableDebtToken} from '../../interfaces/IStableDebtToken.sol';
import {ILendingPool} from '../../interfaces/ILendingPool.sol';
import {VersionedInitializable} from '../libraries/aave-upgradeability/VersionedInitializable.sol';
import {Helpers} from '../libraries/helpers/Helpers.sol';
import {Errors} from '../libraries/helpers/Errors.sol';
import {WadRayMath} from '../libraries/math/WadRayMath.sol';
import {PercentageMath} from '../libraries/math/PercentageMath.sol';
import {ReserveLogic} from '../libraries/logic/ReserveLogic.sol';
import {GenericLogic} from '../libraries/logic/GenericLogic.sol';
import {ValidationLogic} from '../libraries/logic/ValidationLogic.sol';
import {ReserveConfiguration} from '../libraries/configuration/ReserveConfiguration.sol';
import {UserConfiguration} from '../libraries/configuration/UserConfiguration.sol';
import {DataTypes} from '../libraries/types/DataTypes.sol';
import {LendingPoolStorage} from './LendingPoolStorage.sol';
/**
* @title LendingPool contract
* @dev Main point of interaction with an Aave protocol's market
* - Users can:
* # Deposit
* # Withdraw
* # Borrow
* # Repay
* # Swap their loans between variable and stable rate
* # Enable/disable their deposits as collateral rebalance stable rate borrow positions
* # Liquidate positions
* # Execute Flash Loans
* - To be covered by a proxy contract, owned by the LendingPoolAddressesProvider of the specific market
* - All admin functions are callable by the LendingPoolConfigurator contract defined also in the
* LendingPoolAddressesProvider
* @author Aave
**/
contract LendingPool is VersionedInitializable, ILendingPool, LendingPoolStorage {
using SafeMath for uint256;
using WadRayMath for uint256;
using PercentageMath for uint256;
using SafeERC20 for IERC20;
uint256 public constant LENDINGPOOL_REVISION = 0x2;
modifier whenNotPaused() {
_whenNotPaused();
_;
}
modifier onlyLendingPoolConfigurator() {
_onlyLendingPoolConfigurator();
_;
}
function _whenNotPaused() internal view {
require(!_paused, Errors.LP_IS_PAUSED);
}
function _onlyLendingPoolConfigurator() internal view {
require(
_addressesProvider.getLendingPoolConfigurator() == msg.sender,
Errors.LP_CALLER_NOT_LENDING_POOL_CONFIGURATOR
);
}
function getRevision() internal pure override returns (uint256) {
return LENDINGPOOL_REVISION;
}
/**
* @dev Function is invoked by the proxy contract when the LendingPool contract is added to the
* LendingPoolAddressesProvider of the market.
* - Caching the address of the LendingPoolAddressesProvider in order to reduce gas consumption
* on subsequent operations
* @param provider The address of the LendingPoolAddressesProvider
**/
function initialize(ILendingPoolAddressesProvider provider) public initializer {
_addressesProvider = provider;
_maxStableRateBorrowSizePercent = 2500;
_flashLoanPremiumTotal = 9;
_maxNumberOfReserves = 128;
}
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
ValidationLogic.validateDeposit(reserve, amount);
address aToken = reserve.aTokenAddress;
reserve.updateState();
reserve.updateInterestRates(asset, aToken, amount, 0);
IERC20(asset).safeTransferFrom(msg.sender, aToken, amount);
bool isFirstDeposit = IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex);
if (isFirstDeposit) {
_usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true);
emit ReserveUsedAsCollateralEnabled(asset, onBehalfOf);
}
emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode);
}
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external override whenNotPaused returns (uint256) {
DataTypes.ReserveData storage reserve = _reserves[asset];
address aToken = reserve.aTokenAddress;
uint256 userBalance = IAToken(aToken).balanceOf(msg.sender);
uint256 amountToWithdraw = amount;
if (amount == type(uint256).max) {
amountToWithdraw = userBalance;
}
ValidationLogic.validateWithdraw(
asset,
amountToWithdraw,
userBalance,
_reserves,
_usersConfig[msg.sender],
_reservesList,
_reservesCount,
_addressesProvider.getPriceOracle()
);
reserve.updateState();
reserve.updateInterestRates(asset, aToken, 0, amountToWithdraw);
if (amountToWithdraw == userBalance) {
_usersConfig[msg.sender].setUsingAsCollateral(reserve.id, false);
emit ReserveUsedAsCollateralDisabled(asset, msg.sender);
}
IAToken(aToken).burn(msg.sender, to, amountToWithdraw, reserve.liquidityIndex);
emit Withdraw(asset, msg.sender, to, amountToWithdraw);
return amountToWithdraw;
}
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
_executeBorrow(
ExecuteBorrowParams(
asset,
msg.sender,
onBehalfOf,
amount,
interestRateMode,
reserve.aTokenAddress,
referralCode,
true
)
);
}
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external override whenNotPaused returns (uint256) {
DataTypes.ReserveData storage reserve = _reserves[asset];
(uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(onBehalfOf, reserve);
DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode);
ValidationLogic.validateRepay(
reserve,
amount,
interestRateMode,
onBehalfOf,
stableDebt,
variableDebt
);
uint256 paybackAmount =
interestRateMode == DataTypes.InterestRateMode.STABLE ? stableDebt : variableDebt;
if (amount < paybackAmount) {
paybackAmount = amount;
}
reserve.updateState();
if (interestRateMode == DataTypes.InterestRateMode.STABLE) {
IStableDebtToken(reserve.stableDebtTokenAddress).burn(onBehalfOf, paybackAmount);
} else {
IVariableDebtToken(reserve.variableDebtTokenAddress).burn(
onBehalfOf,
paybackAmount,
reserve.variableBorrowIndex
);
}
address aToken = reserve.aTokenAddress;
reserve.updateInterestRates(asset, aToken, paybackAmount, 0);
if (stableDebt.add(variableDebt).sub(paybackAmount) == 0) {
_usersConfig[onBehalfOf].setBorrowing(reserve.id, false);
}
IERC20(asset).safeTransferFrom(msg.sender, aToken, paybackAmount);
IAToken(aToken).handleRepayment(msg.sender, paybackAmount);
emit Repay(asset, onBehalfOf, msg.sender, paybackAmount);
return paybackAmount;
}
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
(uint256 stableDebt, uint256 variableDebt) = Helpers.getUserCurrentDebt(msg.sender, reserve);
DataTypes.InterestRateMode interestRateMode = DataTypes.InterestRateMode(rateMode);
ValidationLogic.validateSwapRateMode(
reserve,
_usersConfig[msg.sender],
stableDebt,
variableDebt,
interestRateMode
);
reserve.updateState();
if (interestRateMode == DataTypes.InterestRateMode.STABLE) {
IStableDebtToken(reserve.stableDebtTokenAddress).burn(msg.sender, stableDebt);
IVariableDebtToken(reserve.variableDebtTokenAddress).mint(
msg.sender,
msg.sender,
stableDebt,
reserve.variableBorrowIndex
);
} else {
IVariableDebtToken(reserve.variableDebtTokenAddress).burn(
msg.sender,
variableDebt,
reserve.variableBorrowIndex
);
IStableDebtToken(reserve.stableDebtTokenAddress).mint(
msg.sender,
msg.sender,
variableDebt,
reserve.currentStableBorrowRate
);
}
reserve.updateInterestRates(asset, reserve.aTokenAddress, 0, 0);
emit Swap(asset, msg.sender, rateMode);
}
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external override whenNotPaused {
DataTypes.ReserveData storage reserve = _reserves[asset];
IERC20 stableDebtToken = IERC20(reserve.stableDebtTokenAddress);
IERC20 variableDebtToken = IERC20(reserve.variableDebtTokenAddress);
address aTokenAddress = reserve.aTokenAddress;
uint256 stableDebt = IERC20(stableDebtToken).balanceOf(user);
ValidationLogic.validateRebalanceStableBorrowRate(
reserve,
asset,
stableDebtToken,
variableDebtToken,
aTokenAddress
);
reserve.updateState();
IStableDebtToken(address(stableDebtToken)).burn(user, stableDebt);
IStableDebtToken(address(stableDebtToken)).mint(
user,
user,
stableDebt,
reserve.currentStableBorrowRate
);
reserve.updateInterestRates(asset, aTokenAddress, 0, 0);
emit RebalanceStableBorrowRate(asset, user);
}
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)
external
override
whenNotPaused
{
DataTypes.ReserveData storage reserve = _reserves[asset];
ValidationLogic.validateSetUseReserveAsCollateral(
reserve,
asset,
useAsCollateral,
_reserves,
_usersConfig[msg.sender],
_reservesList,
_reservesCount,
_addressesProvider.getPriceOracle()
);
_usersConfig[msg.sender].setUsingAsCollateral(reserve.id, useAsCollateral);
if (useAsCollateral) {
emit ReserveUsedAsCollateralEnabled(asset, msg.sender);
} else {
emit ReserveUsedAsCollateralDisabled(asset, msg.sender);
}
}
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external override whenNotPaused {
address collateralManager = _addressesProvider.getLendingPoolCollateralManager();
//solium-disable-next-line
(bool success, bytes memory result) =
collateralManager.delegatecall(
abi.encodeWithSignature(
'liquidationCall(address,address,address,uint256,bool)',
collateralAsset,
debtAsset,
user,
debtToCover,
receiveAToken
)
);
require(success, Errors.LP_LIQUIDATION_CALL_FAILED);
(uint256 returnCode, string memory returnMessage) = abi.decode(result, (uint256, string));
require(returnCode == 0, string(abi.encodePacked(returnMessage)));
}
struct FlashLoanLocalVars {
IFlashLoanReceiver receiver;
address oracle;
uint256 i;
address currentAsset;
address currentATokenAddress;
uint256 currentAmount;
uint256 currentPremium;
uint256 currentAmountPlusPremium;
address debtToken;
}
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external override whenNotPaused {
FlashLoanLocalVars memory vars;
ValidationLogic.validateFlashloan(assets, amounts);
address[] memory aTokenAddresses = new address[](assets.length);
uint256[] memory premiums = new uint256[](assets.length);
vars.receiver = IFlashLoanReceiver(receiverAddress);
for (vars.i = 0; vars.i < assets.length; vars.i++) {
aTokenAddresses[vars.i] = _reserves[assets[vars.i]].aTokenAddress;
premiums[vars.i] = amounts[vars.i].mul(_flashLoanPremiumTotal).div(10000);
IAToken(aTokenAddresses[vars.i]).transferUnderlyingTo(receiverAddress, amounts[vars.i]);
}
require(
vars.receiver.executeOperation(assets, amounts, premiums, msg.sender, params),
Errors.LP_INVALID_FLASH_LOAN_EXECUTOR_RETURN
);
for (vars.i = 0; vars.i < assets.length; vars.i++) {
vars.currentAsset = assets[vars.i];
vars.currentAmount = amounts[vars.i];
vars.currentPremium = premiums[vars.i];
vars.currentATokenAddress = aTokenAddresses[vars.i];
vars.currentAmountPlusPremium = vars.currentAmount.add(vars.currentPremium);
if (DataTypes.InterestRateMode(modes[vars.i]) == DataTypes.InterestRateMode.NONE) {
_reserves[vars.currentAsset].updateState();
_reserves[vars.currentAsset].cumulateToLiquidityIndex(
IERC20(vars.currentATokenAddress).totalSupply(),
vars.currentPremium
);
_reserves[vars.currentAsset].updateInterestRates(
vars.currentAsset,
vars.currentATokenAddress,
vars.currentAmountPlusPremium,
0
);
IERC20(vars.currentAsset).safeTransferFrom(
receiverAddress,
vars.currentATokenAddress,
vars.currentAmountPlusPremium
);
} else {
// If the user chose to not return the funds, the system checks if there is enough collateral and
// eventually opens a debt position
_executeBorrow(
ExecuteBorrowParams(
vars.currentAsset,
msg.sender,
onBehalfOf,
vars.currentAmount,
modes[vars.i],
vars.currentATokenAddress,
referralCode,
false
)
);
}
emit FlashLoan(
receiverAddress,
msg.sender,
vars.currentAsset,
vars.currentAmount,
vars.currentPremium,
referralCode
);
}
}
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset)
external
view
override
returns (DataTypes.ReserveData memory)
{
return _reserves[asset];
}
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
override
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
)
{
(
totalCollateralETH,
totalDebtETH,
ltv,
currentLiquidationThreshold,
healthFactor
) = GenericLogic.calculateUserAccountData(
user,
_reserves,
_usersConfig[user],
_reservesList,
_reservesCount,
_addressesProvider.getPriceOracle()
);
availableBorrowsETH = GenericLogic.calculateAvailableBorrowsETH(
totalCollateralETH,
totalDebtETH,
ltv
);
}
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
override
returns (DataTypes.ReserveConfigurationMap memory)
{
return _reserves[asset].configuration;
}
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
override
returns (DataTypes.UserConfigurationMap memory)
{
return _usersConfig[user];
}
/**
* @dev Returns the normalized income per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset)
external
view
virtual
override
returns (uint256)
{
return _reserves[asset].getNormalizedIncome();
}
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset)
external
view
override
returns (uint256)
{
return _reserves[asset].getNormalizedDebt();
}
/**
* @dev Returns if the LendingPool is paused
*/
function paused() external view override returns (bool) {
return _paused;
}
/**
* @dev Returns the list of the initialized reserves
**/
function getReservesList() external view override returns (address[] memory) {
address[] memory _activeReserves = new address[](_reservesCount);
for (uint256 i = 0; i < _reservesCount; i++) {
_activeReserves[i] = _reservesList[i];
}
return _activeReserves;
}
/**
* @dev Returns the cached LendingPoolAddressesProvider connected to this contract
**/
function getAddressesProvider() external view override returns (ILendingPoolAddressesProvider) {
return _addressesProvider;
}
/**
* @dev Returns the percentage of available liquidity that can be borrowed at once at stable rate
*/
function MAX_STABLE_RATE_BORROW_SIZE_PERCENT() public view returns (uint256) {
return _maxStableRateBorrowSizePercent;
}
/**
* @dev Returns the fee on flash loans
*/
function FLASHLOAN_PREMIUM_TOTAL() public view returns (uint256) {
return _flashLoanPremiumTotal;
}
/**
* @dev Returns the maximum number of reserves supported to be listed in this LendingPool
*/
function MAX_NUMBER_RESERVES() public view returns (uint256) {
return _maxNumberOfReserves;
}
/**
* @dev Validates and finalizes an aToken transfer
* - Only callable by the overlying aToken of the `asset`
* @param asset The address of the underlying asset of the aToken
* @param from The user from which the aTokens are transferred
* @param to The user receiving the aTokens
* @param amount The amount being transferred/withdrawn
* @param balanceFromBefore The aToken balance of the `from` user before the transfer
* @param balanceToBefore The aToken balance of the `to` user before the transfer
*/
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromBefore,
uint256 balanceToBefore
) external override whenNotPaused {
require(msg.sender == _reserves[asset].aTokenAddress, Errors.LP_CALLER_MUST_BE_AN_ATOKEN);
ValidationLogic.validateTransfer(
from,
_reserves,
_usersConfig[from],
_reservesList,
_reservesCount,
_addressesProvider.getPriceOracle()
);
uint256 reserveId = _reserves[asset].id;
if (from != to) {
if (balanceFromBefore.sub(amount) == 0) {
DataTypes.UserConfigurationMap storage fromConfig = _usersConfig[from];
fromConfig.setUsingAsCollateral(reserveId, false);
emit ReserveUsedAsCollateralDisabled(asset, from);
}
if (balanceToBefore == 0 && amount != 0) {
DataTypes.UserConfigurationMap storage toConfig = _usersConfig[to];
toConfig.setUsingAsCollateral(reserveId, true);
emit ReserveUsedAsCollateralEnabled(asset, to);
}
}
}
/**
* @dev Initializes a reserve, activating it, assigning an aToken and debt tokens and an
* interest rate strategy
* - Only callable by the LendingPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param aTokenAddress The address of the aToken that will be assigned to the reserve
* @param stableDebtAddress The address of the StableDebtToken that will be assigned to the reserve
* @param aTokenAddress The address of the VariableDebtToken that will be assigned to the reserve
* @param interestRateStrategyAddress The address of the interest rate strategy contract
**/
function initReserve(
address asset,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external override onlyLendingPoolConfigurator {
require(Address.isContract(asset), Errors.LP_NOT_CONTRACT);
_reserves[asset].init(
aTokenAddress,
stableDebtAddress,
variableDebtAddress,
interestRateStrategyAddress
);
_addReserveToList(asset);
}
/**
* @dev Updates the address of the interest rate strategy contract
* - Only callable by the LendingPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param rateStrategyAddress The address of the interest rate strategy contract
**/
function setReserveInterestRateStrategyAddress(address asset, address rateStrategyAddress)
external
override
onlyLendingPoolConfigurator
{
_reserves[asset].interestRateStrategyAddress = rateStrategyAddress;
}
/**
* @dev Sets the configuration bitmap of the reserve as a whole
* - Only callable by the LendingPoolConfigurator contract
* @param asset The address of the underlying asset of the reserve
* @param configuration The new configuration bitmap
**/
function setConfiguration(address asset, uint256 configuration)
external
override
onlyLendingPoolConfigurator
{
_reserves[asset].configuration.data = configuration;
}
/**
* @dev Set the _pause state of a reserve
* - Only callable by the LendingPoolConfigurator contract
* @param val `true` to pause the reserve, `false` to un-pause it
*/
function setPause(bool val) external override onlyLendingPoolConfigurator {
_paused = val;
if (_paused) {
emit Paused();
} else {
emit Unpaused();
}
}
struct ExecuteBorrowParams {
address asset;
address user;
address onBehalfOf;
uint256 amount;
uint256 interestRateMode;
address aTokenAddress;
uint16 referralCode;
bool releaseUnderlying;
}
function _executeBorrow(ExecuteBorrowParams memory vars) internal {
DataTypes.ReserveData storage reserve = _reserves[vars.asset];
DataTypes.UserConfigurationMap storage userConfig = _usersConfig[vars.onBehalfOf];
address oracle = _addressesProvider.getPriceOracle();
uint256 amountInETH =
IPriceOracleGetter(oracle).getAssetPrice(vars.asset).mul(vars.amount).div(
10**reserve.configuration.getDecimals()
);
ValidationLogic.validateBorrow(
vars.asset,
reserve,
vars.onBehalfOf,
vars.amount,
amountInETH,
vars.interestRateMode,
_maxStableRateBorrowSizePercent,
_reserves,
userConfig,
_reservesList,
_reservesCount,
oracle
);
reserve.updateState();
uint256 currentStableRate = 0;
bool isFirstBorrowing = false;
if (DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE) {
currentStableRate = reserve.currentStableBorrowRate;
isFirstBorrowing = IStableDebtToken(reserve.stableDebtTokenAddress).mint(
vars.user,
vars.onBehalfOf,
vars.amount,
currentStableRate
);
} else {
isFirstBorrowing = IVariableDebtToken(reserve.variableDebtTokenAddress).mint(
vars.user,
vars.onBehalfOf,
vars.amount,
reserve.variableBorrowIndex
);
}
if (isFirstBorrowing) {
userConfig.setBorrowing(reserve.id, true);
}
reserve.updateInterestRates(
vars.asset,
vars.aTokenAddress,
0,
vars.releaseUnderlying ? vars.amount : 0
);
if (vars.releaseUnderlying) {
IAToken(vars.aTokenAddress).transferUnderlyingTo(vars.user, vars.amount);
}
emit Borrow(
vars.asset,
vars.user,
vars.onBehalfOf,
vars.amount,
vars.interestRateMode,
DataTypes.InterestRateMode(vars.interestRateMode) == DataTypes.InterestRateMode.STABLE
? currentStableRate
: reserve.currentVariableBorrowRate,
vars.referralCode
);
}
function _addReserveToList(address asset) internal {
uint256 reservesCount = _reservesCount;
require(reservesCount < _maxNumberOfReserves, Errors.LP_NO_MORE_RESERVES_ALLOWED);
bool reserveAlreadyAdded = _reserves[asset].id != 0 || _reservesList[0] == asset;
if (!reserveAlreadyAdded) {
_reserves[asset].id = uint8(reservesCount);
_reservesList[reservesCount] = asset;
_reservesCount = reservesCount + 1;
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
interface IExchangeAdapter {
event Exchange(
address indexed from,
address indexed to,
address indexed platform,
uint256 fromAmount,
uint256 toAmount
);
function approveExchange(IERC20[] calldata tokens) external;
function exchange(
address from,
address to,
uint256 amount,
uint256 maxSlippage
) external returns (uint256);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ERC20} from '../../dependencies/openzeppelin/contracts/ERC20.sol';
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract MintableDelegationERC20 is ERC20 {
address public delegatee;
constructor(
string memory name,
string memory symbol,
uint8 decimals
) public ERC20(name, symbol) {
_setupDecimals(decimals);
}
/**
* @dev Function to mint tokensp
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(uint256 value) public returns (bool) {
_mint(msg.sender, value);
return true;
}
function delegate(address delegateeAddress) external {
delegatee = delegateeAddress;
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {IUniswapV2Router02} from '../../interfaces/IUniswapV2Router02.sol';
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import {MintableERC20} from '../tokens/MintableERC20.sol';
contract MockUniswapV2Router02 is IUniswapV2Router02 {
mapping(address => uint256) internal _amountToReturn;
mapping(address => uint256) internal _amountToSwap;
mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsIn;
mapping(address => mapping(address => mapping(uint256 => uint256))) internal _amountsOut;
uint256 internal defaultMockValue;
function setAmountToReturn(address reserve, uint256 amount) public {
_amountToReturn[reserve] = amount;
}
function setAmountToSwap(address reserve, uint256 amount) public {
_amountToSwap[reserve] = amount;
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256, /* amountOutMin */
address[] calldata path,
address to,
uint256 /* deadline */
) external override returns (uint256[] memory amounts) {
IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn);
MintableERC20(path[1]).mint(_amountToReturn[path[0]]);
IERC20(path[1]).transfer(to, _amountToReturn[path[0]]);
amounts = new uint256[](path.length);
amounts[0] = amountIn;
amounts[1] = _amountToReturn[path[0]];
}
function swapTokensForExactTokens(
uint256 amountOut,
uint256, /* amountInMax */
address[] calldata path,
address to,
uint256 /* deadline */
) external override returns (uint256[] memory amounts) {
IERC20(path[0]).transferFrom(msg.sender, address(this), _amountToSwap[path[0]]);
MintableERC20(path[1]).mint(amountOut);
IERC20(path[1]).transfer(to, amountOut);
amounts = new uint256[](path.length);
amounts[0] = _amountToSwap[path[0]];
amounts[1] = amountOut;
}
function setAmountOut(
uint256 amountIn,
address reserveIn,
address reserveOut,
uint256 amountOut
) public {
_amountsOut[reserveIn][reserveOut][amountIn] = amountOut;
}
function setAmountIn(
uint256 amountOut,
address reserveIn,
address reserveOut,
uint256 amountIn
) public {
_amountsIn[reserveIn][reserveOut][amountOut] = amountIn;
}
function setDefaultMockValue(uint256 value) public {
defaultMockValue = value;
}
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
override
returns (uint256[] memory)
{
uint256[] memory amounts = new uint256[](path.length);
amounts[0] = amountIn;
amounts[1] = _amountsOut[path[0]][path[1]][amountIn] > 0
? _amountsOut[path[0]][path[1]][amountIn]
: defaultMockValue;
return amounts;
}
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
override
returns (uint256[] memory)
{
uint256[] memory amounts = new uint256[](path.length);
amounts[0] = _amountsIn[path[0]][path[1]][amountOut] > 0
? _amountsIn[path[0]][path[1]][amountOut]
: defaultMockValue;
amounts[1] = amountOut;
return amounts;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
/**
* @title UniswapLiquiditySwapAdapter
* @notice Uniswap V2 Adapter to swap liquidity.
* @author Aave
**/
contract UniswapLiquiditySwapAdapter is BaseUniswapAdapter {
struct PermitParams {
uint256[] amount;
uint256[] deadline;
uint8[] v;
bytes32[] r;
bytes32[] s;
}
struct SwapParams {
address[] assetToSwapToList;
uint256[] minAmountsToReceive;
bool[] swapAllBalance;
PermitParams permitParams;
bool[] useEthPath;
}
constructor(
ILendingPoolAddressesProvider addressesProvider,
IUniswapV2Router02 uniswapRouter,
address wethAddress
) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {}
/**
* @dev Swaps the received reserve amount from the flash loan into the asset specified in the params.
* The received funds from the swap are then deposited into the protocol on behalf of the user.
* The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and
* repay the flash loan.
* @param assets Address of asset to be swapped
* @param amounts Amount of the asset to be swapped
* @param premiums Fee of the flash loan
* @param initiator Address of the user
* @param params Additional variadic field to include extra params. Expected parameters:
* address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited
* uint256[] minAmountsToReceive List of min amounts to be received from the swap
* bool[] swapAllBalance Flag indicating if all the user balance should be swapped
* uint256[] permitAmount List of amounts for the permit signature
* uint256[] deadline List of deadlines for the permit signature
* uint8[] v List of v param for the permit signature
* bytes32[] r List of r param for the permit signature
* bytes32[] s List of s param for the permit signature
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL');
SwapParams memory decodedParams = _decodeParams(params);
require(
assets.length == decodedParams.assetToSwapToList.length &&
assets.length == decodedParams.minAmountsToReceive.length &&
assets.length == decodedParams.swapAllBalance.length &&
assets.length == decodedParams.permitParams.amount.length &&
assets.length == decodedParams.permitParams.deadline.length &&
assets.length == decodedParams.permitParams.v.length &&
assets.length == decodedParams.permitParams.r.length &&
assets.length == decodedParams.permitParams.s.length &&
assets.length == decodedParams.useEthPath.length,
'INCONSISTENT_PARAMS'
);
for (uint256 i = 0; i < assets.length; i++) {
_swapLiquidity(
assets[i],
decodedParams.assetToSwapToList[i],
amounts[i],
premiums[i],
initiator,
decodedParams.minAmountsToReceive[i],
decodedParams.swapAllBalance[i],
PermitSignature(
decodedParams.permitParams.amount[i],
decodedParams.permitParams.deadline[i],
decodedParams.permitParams.v[i],
decodedParams.permitParams.r[i],
decodedParams.permitParams.s[i]
),
decodedParams.useEthPath[i]
);
}
return true;
}
struct SwapAndDepositLocalVars {
uint256 i;
uint256 aTokenInitiatorBalance;
uint256 amountToSwap;
uint256 receivedAmount;
address aToken;
}
/**
* @dev Swaps an amount of an asset to another and deposits the new asset amount on behalf of the user without using
* a flash loan. This method can be used when the temporary transfer of the collateral asset to this contract
* does not affect the user position.
* The user should give this contract allowance to pull the ATokens in order to withdraw the underlying asset and
* perform the swap.
* @param assetToSwapFromList List of addresses of the underlying asset to be swap from
* @param assetToSwapToList List of addresses of the underlying asset to be swap to and deposited
* @param amountToSwapList List of amounts to be swapped. If the amount exceeds the balance, the total balance is used for the swap
* @param minAmountsToReceive List of min amounts to be received from the swap
* @param permitParams List of struct containing the permit signatures
* uint256 permitAmount Amount for the permit signature
* uint256 deadline Deadline for the permit signature
* uint8 v param for the permit signature
* bytes32 r param for the permit signature
* bytes32 s param for the permit signature
* @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise
*/
function swapAndDeposit(
address[] calldata assetToSwapFromList,
address[] calldata assetToSwapToList,
uint256[] calldata amountToSwapList,
uint256[] calldata minAmountsToReceive,
PermitSignature[] calldata permitParams,
bool[] calldata useEthPath
) external {
require(
assetToSwapFromList.length == assetToSwapToList.length &&
assetToSwapFromList.length == amountToSwapList.length &&
assetToSwapFromList.length == minAmountsToReceive.length &&
assetToSwapFromList.length == permitParams.length,
'INCONSISTENT_PARAMS'
);
SwapAndDepositLocalVars memory vars;
for (vars.i = 0; vars.i < assetToSwapFromList.length; vars.i++) {
vars.aToken = _getReserveData(assetToSwapFromList[vars.i]).aTokenAddress;
vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(msg.sender);
vars.amountToSwap = amountToSwapList[vars.i] > vars.aTokenInitiatorBalance
? vars.aTokenInitiatorBalance
: amountToSwapList[vars.i];
_pullAToken(
assetToSwapFromList[vars.i],
vars.aToken,
msg.sender,
vars.amountToSwap,
permitParams[vars.i]
);
vars.receivedAmount = _swapExactTokensForTokens(
assetToSwapFromList[vars.i],
assetToSwapToList[vars.i],
vars.amountToSwap,
minAmountsToReceive[vars.i],
useEthPath[vars.i]
);
// Deposit new reserve
IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), 0);
IERC20(assetToSwapToList[vars.i]).safeApprove(address(LENDING_POOL), vars.receivedAmount);
LENDING_POOL.deposit(assetToSwapToList[vars.i], vars.receivedAmount, msg.sender, 0);
}
}
/**
* @dev Swaps an `amountToSwap` of an asset to another and deposits the funds on behalf of the initiator.
* @param assetFrom Address of the underlying asset to be swap from
* @param assetTo Address of the underlying asset to be swap to and deposited
* @param amount Amount from flash loan
* @param premium Premium of the flash loan
* @param minAmountToReceive Min amount to be received from the swap
* @param swapAllBalance Flag indicating if all the user balance should be swapped
* @param permitSignature List of struct containing the permit signature
* @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise
*/
struct SwapLiquidityLocalVars {
address aToken;
uint256 aTokenInitiatorBalance;
uint256 amountToSwap;
uint256 receivedAmount;
uint256 flashLoanDebt;
uint256 amountToPull;
}
function _swapLiquidity(
address assetFrom,
address assetTo,
uint256 amount,
uint256 premium,
address initiator,
uint256 minAmountToReceive,
bool swapAllBalance,
PermitSignature memory permitSignature,
bool useEthPath
) internal {
SwapLiquidityLocalVars memory vars;
vars.aToken = _getReserveData(assetFrom).aTokenAddress;
vars.aTokenInitiatorBalance = IERC20(vars.aToken).balanceOf(initiator);
vars.amountToSwap = swapAllBalance && vars.aTokenInitiatorBalance.sub(premium) <= amount
? vars.aTokenInitiatorBalance.sub(premium)
: amount;
vars.receivedAmount = _swapExactTokensForTokens(
assetFrom,
assetTo,
vars.amountToSwap,
minAmountToReceive,
useEthPath
);
// Deposit new reserve
IERC20(assetTo).safeApprove(address(LENDING_POOL), 0);
IERC20(assetTo).safeApprove(address(LENDING_POOL), vars.receivedAmount);
LENDING_POOL.deposit(assetTo, vars.receivedAmount, initiator, 0);
vars.flashLoanDebt = amount.add(premium);
vars.amountToPull = vars.amountToSwap.add(premium);
_pullAToken(assetFrom, vars.aToken, initiator, vars.amountToPull, permitSignature);
// Repay flash loan
IERC20(assetFrom).safeApprove(address(LENDING_POOL), 0);
IERC20(assetFrom).safeApprove(address(LENDING_POOL), vars.flashLoanDebt);
}
/**
* @dev Decodes the information encoded in the flash loan params
* @param params Additional variadic field to include extra params. Expected parameters:
* address[] assetToSwapToList List of the addresses of the reserve to be swapped to and deposited
* uint256[] minAmountsToReceive List of min amounts to be received from the swap
* bool[] swapAllBalance Flag indicating if all the user balance should be swapped
* uint256[] permitAmount List of amounts for the permit signature
* uint256[] deadline List of deadlines for the permit signature
* uint8[] v List of v param for the permit signature
* bytes32[] r List of r param for the permit signature
* bytes32[] s List of s param for the permit signature
* bool[] useEthPath true if the swap needs to occur using ETH in the routing, false otherwise
* @return SwapParams struct containing decoded params
*/
function _decodeParams(bytes memory params) internal pure returns (SwapParams memory) {
(
address[] memory assetToSwapToList,
uint256[] memory minAmountsToReceive,
bool[] memory swapAllBalance,
uint256[] memory permitAmount,
uint256[] memory deadline,
uint8[] memory v,
bytes32[] memory r,
bytes32[] memory s,
bool[] memory useEthPath
) =
abi.decode(
params,
(address[], uint256[], bool[], uint256[], uint256[], uint8[], bytes32[], bytes32[], bool[])
);
return
SwapParams(
assetToSwapToList,
minAmountsToReceive,
swapAllBalance,
PermitParams(permitAmount, deadline, v, r, s),
useEthPath
);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {BaseUniswapAdapter} from './BaseUniswapAdapter.sol';
import {ILendingPoolAddressesProvider} from '../interfaces/ILendingPoolAddressesProvider.sol';
import {IUniswapV2Router02} from '../interfaces/IUniswapV2Router02.sol';
import {IERC20} from '../dependencies/openzeppelin/contracts/IERC20.sol';
import {DataTypes} from '../protocol/libraries/types/DataTypes.sol';
import {Helpers} from '../protocol/libraries/helpers/Helpers.sol';
import {IPriceOracleGetter} from '../interfaces/IPriceOracleGetter.sol';
import {IAToken} from '../interfaces/IAToken.sol';
import {ReserveConfiguration} from '../protocol/libraries/configuration/ReserveConfiguration.sol';
/**
* @title UniswapLiquiditySwapAdapter
* @notice Uniswap V2 Adapter to swap liquidity.
* @author Aave
**/
contract FlashLiquidationAdapter is BaseUniswapAdapter {
using ReserveConfiguration for DataTypes.ReserveConfigurationMap;
uint256 internal constant LIQUIDATION_CLOSE_FACTOR_PERCENT = 5000;
struct LiquidationParams {
address collateralAsset;
address borrowedAsset;
address user;
uint256 debtToCover;
bool useEthPath;
}
struct LiquidationCallLocalVars {
uint256 initFlashBorrowedBalance;
uint256 diffFlashBorrowedBalance;
uint256 initCollateralBalance;
uint256 diffCollateralBalance;
uint256 flashLoanDebt;
uint256 soldAmount;
uint256 remainingTokens;
uint256 borrowedAssetLeftovers;
}
constructor(
ILendingPoolAddressesProvider addressesProvider,
IUniswapV2Router02 uniswapRouter,
address wethAddress
) public BaseUniswapAdapter(addressesProvider, uniswapRouter, wethAddress) {}
/**
* @dev Liquidate a non-healthy position collateral-wise, with a Health Factor below 1, using Flash Loan and Uniswap to repay flash loan premium.
* - The caller (liquidator) with a flash loan covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk minus the flash loan premium.
* @param assets Address of asset to be swapped
* @param amounts Amount of the asset to be swapped
* @param premiums Fee of the flash loan
* @param initiator Address of the caller
* @param params Additional variadic field to include extra params. Expected parameters:
* address collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium
* address borrowedAsset The asset that must be covered
* address user The user address with a Health Factor below 1
* uint256 debtToCover The amount of debt to cover
* bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap
*/
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
) external override returns (bool) {
require(msg.sender == address(LENDING_POOL), 'CALLER_MUST_BE_LENDING_POOL');
LiquidationParams memory decodedParams = _decodeParams(params);
require(assets.length == 1 && assets[0] == decodedParams.borrowedAsset, 'INCONSISTENT_PARAMS');
_liquidateAndSwap(
decodedParams.collateralAsset,
decodedParams.borrowedAsset,
decodedParams.user,
decodedParams.debtToCover,
decodedParams.useEthPath,
amounts[0],
premiums[0],
initiator
);
return true;
}
/**
* @dev
* @param collateralAsset The collateral asset to release and will be exchanged to pay the flash loan premium
* @param borrowedAsset The asset that must be covered
* @param user The user address with a Health Factor below 1
* @param debtToCover The amount of debt to coverage, can be max(-1) to liquidate all possible debt
* @param useEthPath true if the swap needs to occur using ETH in the routing, false otherwise
* @param flashBorrowedAmount Amount of asset requested at the flash loan to liquidate the user position
* @param premium Fee of the requested flash loan
* @param initiator Address of the caller
*/
function _liquidateAndSwap(
address collateralAsset,
address borrowedAsset,
address user,
uint256 debtToCover,
bool useEthPath,
uint256 flashBorrowedAmount,
uint256 premium,
address initiator
) internal {
LiquidationCallLocalVars memory vars;
vars.initCollateralBalance = IERC20(collateralAsset).balanceOf(address(this));
if (collateralAsset != borrowedAsset) {
vars.initFlashBorrowedBalance = IERC20(borrowedAsset).balanceOf(address(this));
// Track leftover balance to rescue funds in case of external transfers into this contract
vars.borrowedAssetLeftovers = vars.initFlashBorrowedBalance.sub(flashBorrowedAmount);
}
vars.flashLoanDebt = flashBorrowedAmount.add(premium);
// Approve LendingPool to use debt token for liquidation
IERC20(borrowedAsset).approve(address(LENDING_POOL), debtToCover);
// Liquidate the user position and release the underlying collateral
LENDING_POOL.liquidationCall(collateralAsset, borrowedAsset, user, debtToCover, false);
// Discover the liquidated tokens
uint256 collateralBalanceAfter = IERC20(collateralAsset).balanceOf(address(this));
// Track only collateral released, not current asset balance of the contract
vars.diffCollateralBalance = collateralBalanceAfter.sub(vars.initCollateralBalance);
if (collateralAsset != borrowedAsset) {
// Discover flash loan balance after the liquidation
uint256 flashBorrowedAssetAfter = IERC20(borrowedAsset).balanceOf(address(this));
// Use only flash loan borrowed assets, not current asset balance of the contract
vars.diffFlashBorrowedBalance = flashBorrowedAssetAfter.sub(vars.borrowedAssetLeftovers);
// Swap released collateral into the debt asset, to repay the flash loan
vars.soldAmount = _swapTokensForExactTokens(
collateralAsset,
borrowedAsset,
vars.diffCollateralBalance,
vars.flashLoanDebt.sub(vars.diffFlashBorrowedBalance),
useEthPath
);
vars.remainingTokens = vars.diffCollateralBalance.sub(vars.soldAmount);
} else {
vars.remainingTokens = vars.diffCollateralBalance.sub(premium);
}
// Allow repay of flash loan
IERC20(borrowedAsset).approve(address(LENDING_POOL), vars.flashLoanDebt);
// Transfer remaining tokens to initiator
if (vars.remainingTokens > 0) {
IERC20(collateralAsset).transfer(initiator, vars.remainingTokens);
}
}
/**
* @dev Decodes the information encoded in the flash loan params
* @param params Additional variadic field to include extra params. Expected parameters:
* address collateralAsset The collateral asset to claim
* address borrowedAsset The asset that must be covered and will be exchanged to pay the flash loan premium
* address user The user address with a Health Factor below 1
* uint256 debtToCover The amount of debt to cover
* bool useEthPath Use WETH as connector path between the collateralAsset and borrowedAsset at Uniswap
* @return LiquidationParams struct containing decoded params
*/
function _decodeParams(bytes memory params) internal pure returns (LiquidationParams memory) {
(
address collateralAsset,
address borrowedAsset,
address user,
uint256 debtToCover,
bool useEthPath
) = abi.decode(params, (address, address, address, uint256, bool));
return LiquidationParams(collateralAsset, borrowedAsset, user, debtToCover, useEthPath);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './BaseAdminUpgradeabilityProxy.sol';
import './InitializableUpgradeabilityProxy.sol';
/**
* @title InitializableAdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for
* initializing the implementation, admin, and init data.
*/
contract InitializableAdminUpgradeabilityProxy is
BaseAdminUpgradeabilityProxy,
InitializableUpgradeabilityProxy
{
/**
* Contract initializer.
* @param logic address of the initial implementation.
* @param admin Address of the proxy administrator.
* @param data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
function initialize(
address logic,
address admin,
bytes memory data
) public payable {
require(_implementation() == address(0));
InitializableUpgradeabilityProxy.initialize(logic, data);
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(admin);
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) {
BaseAdminUpgradeabilityProxy._willFallback();
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './UpgradeabilityProxy.sol';
/**
* @title BaseAdminUpgradeabilityProxy
* @dev This contract combines an upgradeability proxy with an authorization
* mechanism for administrative tasks.
* All external functions in this contract must be guarded by the
* `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity
* feature proposal that would enable this to be done automatically.
*/
contract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Emitted when the administration has been transferred.
* @param previousAdmin Address of the previous admin.
* @param newAdmin Address of the new admin.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Modifier to check whether the `msg.sender` is the admin.
* If it is, it will run the function. Otherwise, it will delegate the call
* to the implementation.
*/
modifier ifAdmin() {
if (msg.sender == _admin()) {
_;
} else {
_fallback();
}
}
/**
* @return The address of the proxy admin.
*/
function admin() external ifAdmin returns (address) {
return _admin();
}
/**
* @return The address of the implementation.
*/
function implementation() external ifAdmin returns (address) {
return _implementation();
}
/**
* @dev Changes the admin of the proxy.
* Only the current admin can call this function.
* @param newAdmin Address to transfer proxy administration to.
*/
function changeAdmin(address newAdmin) external ifAdmin {
require(newAdmin != address(0), 'Cannot change the admin of a proxy to the zero address');
emit AdminChanged(_admin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev Upgrade the backing implementation of the proxy.
* Only the admin can call this function.
* @param newImplementation Address of the new implementation.
*/
function upgradeTo(address newImplementation) external ifAdmin {
_upgradeTo(newImplementation);
}
/**
* @dev Upgrade the backing implementation of the proxy and call a function
* on the new implementation.
* This is useful to initialize the proxied contract.
* @param newImplementation Address of the new implementation.
* @param data Data to send as msg.data in the low level call.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
*/
function upgradeToAndCall(address newImplementation, bytes calldata data)
external
payable
ifAdmin
{
_upgradeTo(newImplementation);
(bool success, ) = newImplementation.delegatecall(data);
require(success);
}
/**
* @return adm The admin slot.
*/
function _admin() internal view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
//solium-disable-next-line
assembly {
adm := sload(slot)
}
}
/**
* @dev Sets the address of the proxy admin.
* @param newAdmin Address of the new proxy admin.
*/
function _setAdmin(address newAdmin) internal {
bytes32 slot = ADMIN_SLOT;
//solium-disable-next-line
assembly {
sstore(slot, newAdmin)
}
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal virtual override {
require(msg.sender != _admin(), 'Cannot call fallback function from the proxy admin');
super._willFallback();
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './BaseUpgradeabilityProxy.sol';
/**
* @title UpgradeabilityProxy
* @dev Extends BaseUpgradeabilityProxy with a constructor for initializing
* implementation and init data.
*/
contract UpgradeabilityProxy is BaseUpgradeabilityProxy {
/**
* @dev Contract constructor.
* @param _logic Address of the initial implementation.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(address _logic, bytes memory _data) public payable {
assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));
_setImplementation(_logic);
if (_data.length > 0) {
(bool success, ) = _logic.delegatecall(_data);
require(success);
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import './BaseAdminUpgradeabilityProxy.sol';
/**
* @title AdminUpgradeabilityProxy
* @dev Extends from BaseAdminUpgradeabilityProxy with a constructor for
* initializing the implementation, admin, and init data.
*/
contract AdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy, UpgradeabilityProxy {
/**
* Contract constructor.
* @param _logic address of the initial implementation.
* @param _admin Address of the proxy administrator.
* @param _data Data to send as msg.data to the implementation to initialize the proxied contract.
* It should include the signature and the parameters of the function to be called, as described in
* https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.
* This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.
*/
constructor(
address _logic,
address _admin,
bytes memory _data
) public payable UpgradeabilityProxy(_logic, _data) {
assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));
_setAdmin(_admin);
}
/**
* @dev Only fall back when the sender is not the admin.
*/
function _willFallback() internal override(BaseAdminUpgradeabilityProxy, Proxy) {
BaseAdminUpgradeabilityProxy._willFallback();
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol';
// Prettier ignore to prevent buidler flatter bug
// prettier-ignore
import {InitializableImmutableAdminUpgradeabilityProxy} from '../libraries/aave-upgradeability/InitializableImmutableAdminUpgradeabilityProxy.sol';
import {ILendingPoolAddressesProvider} from '../../interfaces/ILendingPoolAddressesProvider.sol';
/**
* @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
**/
contract LendingPoolAddressesProvider is Ownable, ILendingPoolAddressesProvider {
string private _marketId;
mapping(bytes32 => address) private _addresses;
bytes32 private constant LENDING_POOL = 'LENDING_POOL';
bytes32 private constant LENDING_POOL_CONFIGURATOR = 'LENDING_POOL_CONFIGURATOR';
bytes32 private constant POOL_ADMIN = 'POOL_ADMIN';
bytes32 private constant EMERGENCY_ADMIN = 'EMERGENCY_ADMIN';
bytes32 private constant LENDING_POOL_COLLATERAL_MANAGER = 'COLLATERAL_MANAGER';
bytes32 private constant PRICE_ORACLE = 'PRICE_ORACLE';
bytes32 private constant LENDING_RATE_ORACLE = 'LENDING_RATE_ORACLE';
constructor(string memory marketId) public {
_setMarketId(marketId);
}
/**
* @dev Returns the id of the Aave market to which this contracts points to
* @return The market id
**/
function getMarketId() external view override returns (string memory) {
return _marketId;
}
/**
* @dev Allows to set the market which this LendingPoolAddressesProvider represents
* @param marketId The market id
*/
function setMarketId(string memory marketId) external override onlyOwner {
_setMarketId(marketId);
}
/**
* @dev General function to update the implementation of a proxy registered with
* certain `id`. If there is no proxy registered, it will instantiate one and
* set as implementation the `implementationAddress`
* IMPORTANT Use this function carefully, only for ids that don't have an explicit
* setter function, in order to avoid unexpected consequences
* @param id The id
* @param implementationAddress The address of the new implementation
*/
function setAddressAsProxy(bytes32 id, address implementationAddress)
external
override
onlyOwner
{
_updateImpl(id, implementationAddress);
emit AddressSet(id, implementationAddress, true);
}
/**
* @dev Sets an address for an id replacing the address saved in the addresses map
* IMPORTANT Use this function carefully, as it will do a hard replacement
* @param id The id
* @param newAddress The address to set
*/
function setAddress(bytes32 id, address newAddress) external override onlyOwner {
_addresses[id] = newAddress;
emit AddressSet(id, newAddress, false);
}
/**
* @dev Returns an address by id
* @return The address
*/
function getAddress(bytes32 id) public view override returns (address) {
return _addresses[id];
}
/**
* @dev Returns the address of the LendingPool proxy
* @return The LendingPool proxy address
**/
function getLendingPool() external view override returns (address) {
return getAddress(LENDING_POOL);
}
/**
* @dev Updates the implementation of the LendingPool, or creates the proxy
* setting the new `pool` implementation on the first time calling it
* @param pool The new LendingPool implementation
**/
function setLendingPoolImpl(address pool) external override onlyOwner {
_updateImpl(LENDING_POOL, pool);
emit LendingPoolUpdated(pool);
}
/**
* @dev Returns the address of the LendingPoolConfigurator proxy
* @return The LendingPoolConfigurator proxy address
**/
function getLendingPoolConfigurator() external view override returns (address) {
return getAddress(LENDING_POOL_CONFIGURATOR);
}
/**
* @dev Updates the implementation of the LendingPoolConfigurator, or creates the proxy
* setting the new `configurator` implementation on the first time calling it
* @param configurator The new LendingPoolConfigurator implementation
**/
function setLendingPoolConfiguratorImpl(address configurator) external override onlyOwner {
_updateImpl(LENDING_POOL_CONFIGURATOR, configurator);
emit LendingPoolConfiguratorUpdated(configurator);
}
/**
* @dev Returns the address of the LendingPoolCollateralManager. Since the manager is used
* through delegateCall within the LendingPool contract, the proxy contract pattern does not work properly hence
* the addresses are changed directly
* @return The address of the LendingPoolCollateralManager
**/
function getLendingPoolCollateralManager() external view override returns (address) {
return getAddress(LENDING_POOL_COLLATERAL_MANAGER);
}
/**
* @dev Updates the address of the LendingPoolCollateralManager
* @param manager The new LendingPoolCollateralManager address
**/
function setLendingPoolCollateralManager(address manager) external override onlyOwner {
_addresses[LENDING_POOL_COLLATERAL_MANAGER] = manager;
emit LendingPoolCollateralManagerUpdated(manager);
}
/**
* @dev The functions below are getters/setters of addresses that are outside the context
* of the protocol hence the upgradable proxy pattern is not used
**/
function getPoolAdmin() external view override returns (address) {
return getAddress(POOL_ADMIN);
}
function setPoolAdmin(address admin) external override onlyOwner {
_addresses[POOL_ADMIN] = admin;
emit ConfigurationAdminUpdated(admin);
}
function getEmergencyAdmin() external view override returns (address) {
return getAddress(EMERGENCY_ADMIN);
}
function setEmergencyAdmin(address emergencyAdmin) external override onlyOwner {
_addresses[EMERGENCY_ADMIN] = emergencyAdmin;
emit EmergencyAdminUpdated(emergencyAdmin);
}
function getPriceOracle() external view override returns (address) {
return getAddress(PRICE_ORACLE);
}
function setPriceOracle(address priceOracle) external override onlyOwner {
_addresses[PRICE_ORACLE] = priceOracle;
emit PriceOracleUpdated(priceOracle);
}
function getLendingRateOracle() external view override returns (address) {
return getAddress(LENDING_RATE_ORACLE);
}
function setLendingRateOracle(address lendingRateOracle) external override onlyOwner {
_addresses[LENDING_RATE_ORACLE] = lendingRateOracle;
emit LendingRateOracleUpdated(lendingRateOracle);
}
/**
* @dev Internal function to update the implementation of a specific proxied component of the protocol
* - If there is no proxy registered in the given `id`, it creates the proxy setting `newAdress`
* as implementation and calls the initialize() function on the proxy
* - If there is already a proxy registered, it just updates the implementation to `newAddress` and
* calls the initialize() function via upgradeToAndCall() in the proxy
* @param id The id of the proxy to be updated
* @param newAddress The address of the new implementation
**/
function _updateImpl(bytes32 id, address newAddress) internal {
address payable proxyAddress = payable(_addresses[id]);
InitializableImmutableAdminUpgradeabilityProxy proxy =
InitializableImmutableAdminUpgradeabilityProxy(proxyAddress);
bytes memory params = abi.encodeWithSignature('initialize(address)', address(this));
if (proxyAddress == address(0)) {
proxy = new InitializableImmutableAdminUpgradeabilityProxy(address(this));
proxy.initialize(newAddress, params);
_addresses[id] = address(proxy);
emit ProxyCreated(id, address(proxy));
} else {
proxy.upgradeToAndCall(newAddress, params);
}
}
function _setMarketId(string memory marketId) internal {
_marketId = marketId;
emit MarketIdSet(marketId);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {LendingPool} from '../protocol/lendingpool/LendingPool.sol';
import {
LendingPoolAddressesProvider
} from '../protocol/configuration/LendingPoolAddressesProvider.sol';
import {LendingPoolConfigurator} from '../protocol/lendingpool/LendingPoolConfigurator.sol';
import {AToken} from '../protocol/tokenization/AToken.sol';
import {
DefaultReserveInterestRateStrategy
} from '../protocol/lendingpool/DefaultReserveInterestRateStrategy.sol';
import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol';
import {StringLib} from './StringLib.sol';
contract ATokensAndRatesHelper is Ownable {
address payable private pool;
address private addressesProvider;
address private poolConfigurator;
event deployedContracts(address aToken, address strategy);
struct InitDeploymentInput {
address asset;
uint256[6] rates;
}
struct ConfigureReserveInput {
address asset;
uint256 baseLTV;
uint256 liquidationThreshold;
uint256 liquidationBonus;
uint256 reserveFactor;
bool stableBorrowingEnabled;
}
constructor(
address payable _pool,
address _addressesProvider,
address _poolConfigurator
) public {
pool = _pool;
addressesProvider = _addressesProvider;
poolConfigurator = _poolConfigurator;
}
function initDeployment(InitDeploymentInput[] calldata inputParams) external onlyOwner {
for (uint256 i = 0; i < inputParams.length; i++) {
emit deployedContracts(
address(new AToken()),
address(
new DefaultReserveInterestRateStrategy(
LendingPoolAddressesProvider(addressesProvider),
inputParams[i].rates[0],
inputParams[i].rates[1],
inputParams[i].rates[2],
inputParams[i].rates[3],
inputParams[i].rates[4],
inputParams[i].rates[5]
)
)
);
}
}
function configureReserves(ConfigureReserveInput[] calldata inputParams) external onlyOwner {
LendingPoolConfigurator configurator = LendingPoolConfigurator(poolConfigurator);
for (uint256 i = 0; i < inputParams.length; i++) {
configurator.configureReserveAsCollateral(
inputParams[i].asset,
inputParams[i].baseLTV,
inputParams[i].liquidationThreshold,
inputParams[i].liquidationBonus
);
configurator.enableBorrowingOnReserve(
inputParams[i].asset,
inputParams[i].stableBorrowingEnabled
);
configurator.setReserveFactor(inputParams[i].asset, inputParams[i].reserveFactor);
}
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
library StringLib {
function concat(string memory a, string memory b) internal pure returns (string memory) {
return string(abi.encodePacked(a, b));
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import {StableDebtToken} from '../protocol/tokenization/StableDebtToken.sol';
import {VariableDebtToken} from '../protocol/tokenization/VariableDebtToken.sol';
import {LendingRateOracle} from '../mocks/oracle/LendingRateOracle.sol';
import {Ownable} from '../dependencies/openzeppelin/contracts/Ownable.sol';
import {StringLib} from './StringLib.sol';
contract StableAndVariableTokensHelper is Ownable {
address payable private pool;
address private addressesProvider;
event deployedContracts(address stableToken, address variableToken);
constructor(address payable _pool, address _addressesProvider) public {
pool = _pool;
addressesProvider = _addressesProvider;
}
function initDeployment(address[] calldata tokens, string[] calldata symbols) external onlyOwner {
require(tokens.length == symbols.length, 'Arrays not same length');
require(pool != address(0), 'Pool can not be zero address');
for (uint256 i = 0; i < tokens.length; i++) {
emit deployedContracts(address(new StableDebtToken()), address(new VariableDebtToken()));
}
}
function setOracleBorrowRates(
address[] calldata assets,
uint256[] calldata rates,
address oracle
) external onlyOwner {
require(assets.length == rates.length, 'Arrays not same length');
for (uint256 i = 0; i < assets.length; i++) {
// LendingRateOracle owner must be this contract
LendingRateOracle(oracle).setMarketBorrowRate(assets[i], rates[i]);
}
}
function setOracleOwnership(address oracle, address admin) external onlyOwner {
require(admin != address(0), 'owner can not be zero');
require(LendingRateOracle(oracle).owner() == address(this), 'helper is not owner');
LendingRateOracle(oracle).transferOwnership(admin);
}
}
// SPDX-License-Identifier: agpl-3.0
pragma solidity 0.6.12;
import {ILendingRateOracle} from '../../interfaces/ILendingRateOracle.sol';
import {Ownable} from '../../dependencies/openzeppelin/contracts/Ownable.sol';
contract LendingRateOracle is ILendingRateOracle, Ownable {
mapping(address => uint256) borrowRates;
mapping(address => uint256) liquidityRates;
function getMarketBorrowRate(address _asset) external view override returns (uint256) {
return borrowRates[_asset];
}
function setMarketBorrowRate(address _asset, uint256 _rate) external override onlyOwner {
borrowRates[_asset] = _rate;
}
function getMarketLiquidityRate(address _asset) external view returns (uint256) {
return liquidityRates[_asset];
}
function setMarketLiquidityRate(address _asset, uint256 _rate) external onlyOwner {
liquidityRates[_asset] = _rate;
}
} | * @dev Gets the decimals of the underlying asset of the reserve @param self The reserve configuration @return The decimals of the asset/ | function getDecimals(DataTypes.ReserveConfigurationMap storage self)
internal
view
returns (uint256)
{
return (self.data & ~DECIMALS_MASK) >> RESERVE_DECIMALS_START_BIT_POSITION;
}
| 68,392 | [
1,
3002,
326,
15105,
434,
326,
6808,
3310,
434,
326,
20501,
225,
365,
1021,
20501,
1664,
327,
1021,
15105,
434,
326,
3310,
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
]
| [
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,
225,
445,
336,
31809,
12,
751,
2016,
18,
607,
6527,
1750,
863,
2502,
365,
13,
203,
565,
2713,
203,
565,
1476,
203,
565,
1135,
261,
11890,
5034,
13,
203,
225,
288,
203,
565,
327,
261,
2890,
18,
892,
473,
4871,
23816,
55,
67,
11704,
13,
1671,
2438,
2123,
3412,
67,
23816,
55,
67,
7570,
67,
15650,
67,
15258,
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
]
|
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
contract PlagueEvents {
//infective person
event onInfectiveStage
(
address indexed player,
uint256 indexed rndNo,
uint256 keys,
uint256 eth,
uint256 timeStamp,
address indexed inveter
);
// become leader during second stage
event onDevelopmentStage
(
address indexed player,
uint256 indexed rndNo,
uint256 eth,
uint256 timeStamp,
address indexed inveter
);
// award
event onAward
(
address indexed player,
uint256 indexed rndNo,
uint256 eth,
uint256 timeStamp
);
}
contract Plague is PlagueEvents{
using SafeMath for *;
using KeysCalc for uint256;
struct Round {
uint256 eth; // total eth
uint256 keys; // total keys
uint256 startTime; // end time
uint256 endTime; // end time
uint256 infectiveEndTime; // infective end time
address leader; // leader
address infectLastPlayer; // the player will award 10% eth
address [11] lastInfective; // the lastest 11 infective
address [4] loseInfective; // the lose infective
bool [11] infectiveAward_m; //
uint256 totalInfective; // the count of this round
uint256 inveterAmount; // remain inveter amount of this round
uint256 lastRoundReward; // last round remain eth 10% + eth 4% - inveterAmount + last remain award
uint256 exAward; // development award
}
struct PlayerRound {
uint256 eth; // eth player has added to round
uint256 keys; // keys
uint256 withdraw; // how many eth has been withdraw
uint256 getInveterAmount; // inverter amount
uint256 hasGetAwardAmount; // player has get award amount
}
uint256 public rndNo = 1; // current round number
uint256 public totalEth = 0; // total eth in all round
uint256 constant private rndInfectiveStage_ = 10 minutes; // round timer at iinfective stage12 hours;
uint256 constant private rndInfectiveReadyTime_ = 1 minutes; // round timer at infective stage ready time
uint256 constant private rndDevelopmentStage_ = 3 minutes; // round timer at development stage 30 minutes;
uint256 constant private rndDevelopmentReadyTime_ = 1 minutes; // round timer at development stage ready time 1 hours;
uint256 constant private allKeys_ = 100 * (10 ** 18); // all keys count
uint256 constant private allEths_ = 7500773437500000; // all eths count
uint256 constant private rndIncreaseTime_ = 3 minutes; // increase time 3 hours
uint256 constant private developmentAwardPercent = 1; // 0.1% reduction every 3 hours
mapping (uint256 => Round) public round_m; // (rndNo => Round)
mapping (uint256 => mapping (address => PlayerRound)) public playerRound_m; // (rndNo => addr => PlayerRound)
address public owner; // owner address
address public receiver = address(0); // receive eth address
uint256 public ownerWithdraw = 0; // how many eth has been withdraw by owner
bool public isStartGame = false; // start game flag
constructor()
public
{
owner = msg.sender;
}
/**
* @dev prevents contracts from interacting
*/
modifier onlyHuman()
{
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth)
{
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
/**
* @dev only owner
*/
modifier onlyOwner()
{
require(owner == msg.sender, "only owner can do it");
_;
}
/**
* @dev It must be human beings to call the function.
*/
function isHuman(address _addr) private view returns (bool)
{
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
return _codeLength == 0;
}
/**
* @dev player infect a person at current round
*
*/
function buyKeys(address _inveter) private
{
uint256 _eth = msg.value;
uint256 _now = now;
uint256 _rndNo = rndNo;
uint256 _ethUse = msg.value;
// start next round?
if (_now > round_m[_rndNo].endTime)
{
require(round_m[_rndNo].endTime + rndDevelopmentReadyTime_ < _now, "we should wait some times");
uint256 lastAwardEth = (round_m[_rndNo].eth.mul(14) / 100).sub(round_m[_rndNo].inveterAmount);
if(round_m[_rndNo].totalInfective < round_m[_rndNo].lastInfective.length.sub(1))
{
uint256 nextPlayersAward = round_m[_rndNo].lastInfective.length.sub(1).sub(round_m[_rndNo].totalInfective);
uint256 _totalAward = round_m[_rndNo].eth.mul(30) / 100;
_totalAward = _totalAward.add(round_m[_rndNo].lastRoundReward);
if(round_m[_rndNo].infectLastPlayer != address(0))
{
lastAwardEth = lastAwardEth.add(nextPlayersAward.mul(_totalAward.mul(3)/100));
}
else
{
lastAwardEth = lastAwardEth.add(nextPlayersAward.mul(_totalAward.mul(4)/100));
}
}
_rndNo = _rndNo.add(1);
rndNo = _rndNo;
round_m[_rndNo].startTime = _now;
round_m[_rndNo].endTime = _now + rndInfectiveStage_;
round_m[_rndNo].totalInfective = 0;
round_m[_rndNo].lastRoundReward = lastAwardEth;
}
// infective or second stage
if (round_m[_rndNo].keys < allKeys_)
{
// infection stage
uint256 _keys = (round_m[_rndNo].eth).keysRec(_eth);
if (_keys.add(round_m[_rndNo].keys) >= allKeys_)
{
_keys = allKeys_.sub(round_m[_rndNo].keys);
if (round_m[_rndNo].eth >= allEths_)
{
_ethUse = 0;
}
else {
_ethUse = (allEths_).sub(round_m[_rndNo].eth);
}
if (_eth > _ethUse)
{
// refund
msg.sender.transfer(_eth.sub(_ethUse));
}
else {
// fix
_ethUse = _eth;
}
// first stage is over, record current time
round_m[_rndNo].infectiveEndTime = _now.add(rndInfectiveReadyTime_);
round_m[_rndNo].endTime = _now.add(rndDevelopmentStage_).add(rndInfectiveReadyTime_);
round_m[_rndNo].infectLastPlayer = msg.sender;
}
else
{
require (_keys >= 1 * 10 ** 19, "at least 10 thound people");
round_m[_rndNo].endTime = _now + rndInfectiveStage_;
}
round_m[_rndNo].leader = msg.sender;
// update playerRound
playerRound_m[_rndNo][msg.sender].keys = _keys.add(playerRound_m[_rndNo][msg.sender].keys);
playerRound_m[_rndNo][msg.sender].eth = _ethUse.add(playerRound_m[_rndNo][msg.sender].eth);
// update round
round_m[_rndNo].keys = _keys.add(round_m[_rndNo].keys);
round_m[_rndNo].eth = _ethUse.add(round_m[_rndNo].eth);
// update global variable
totalEth = _ethUse.add(totalEth);
// event
emit PlagueEvents.onInfectiveStage
(
msg.sender,
_rndNo,
_keys,
_ethUse,
_now,
_inveter
);
} else {
// second stage
require(round_m[_rndNo].infectiveEndTime < _now, "The virus is being prepared...");
// increase 0.05 Ether every 3 hours
_ethUse = (((_now.sub(round_m[_rndNo].infectiveEndTime)) / rndIncreaseTime_).mul(5 * 10 ** 16)).add((5 * 10 ** 16));
require(_eth >= _ethUse, "Ether amount is wrong");
if(_eth > _ethUse)
{
msg.sender.transfer(_eth.sub(_ethUse));
}
round_m[_rndNo].endTime = _now + rndDevelopmentStage_;
round_m[_rndNo].leader = msg.sender;
// update playerRound
playerRound_m[_rndNo][msg.sender].eth = _ethUse.add(playerRound_m[_rndNo][msg.sender].eth);
// update round
round_m[_rndNo].eth = _ethUse.add(round_m[_rndNo].eth);
// update global variable
totalEth = _ethUse.add(totalEth);
// update development award
uint256 _exAwardPercent = ((_now.sub(round_m[_rndNo].infectiveEndTime)) / rndIncreaseTime_).mul(developmentAwardPercent).add(developmentAwardPercent);
if(_exAwardPercent >= 410)
{
_exAwardPercent = 410;
}
round_m[_rndNo].exAward = (_exAwardPercent.mul(_ethUse) / 1000).add(round_m[_rndNo].exAward);
// event
emit PlagueEvents.onDevelopmentStage
(
msg.sender,
_rndNo,
_ethUse,
_now,
_inveter
);
}
// caculate share inveter amount
if(_inveter != address(0) && isHuman(_inveter))
{
playerRound_m[_rndNo][_inveter].getInveterAmount = playerRound_m[_rndNo][_inveter].getInveterAmount.add(_ethUse.mul(10) / 100);
round_m[_rndNo].inveterAmount = round_m[_rndNo].inveterAmount.add(_ethUse.mul(10) / 100);
}
round_m[_rndNo].loseInfective[round_m[_rndNo].totalInfective % 4] = round_m[_rndNo].lastInfective[round_m[_rndNo].totalInfective % 11];
round_m[_rndNo].lastInfective[round_m[_rndNo].totalInfective % 11] = msg.sender;
round_m[_rndNo].totalInfective = round_m[_rndNo].totalInfective.add(1);
}
/**
* @dev recommend a player
*/
function buyKeyByAddr(address _inveter)
onlyHuman()
isWithinLimits(msg.value)
public
payable
{
require(isStartGame == true, "The game hasn't started yet.");
buyKeys(_inveter);
}
/**
* @dev play
*/
function()
onlyHuman()
isWithinLimits(msg.value)
public
payable
{
require(isStartGame == true, "The game hasn't started yet.");
buyKeys(address(0));
}
/**
* @dev Award by rndNo.
* 0x80ec35ff
* 0x80ec35ff0000000000000000000000000000000000000000000000000000000000000001
*/
function awardByRndNo(uint256 _rndNo)
onlyHuman()
public
{
require(isStartGame == true, "The game hasn't started yet.");
require(_rndNo <= rndNo, "You're running too fast");
uint256 _ethOut = 0;
uint256 _totalAward = round_m[_rndNo].eth.mul(30) / 100;
_totalAward = _totalAward.add(round_m[_rndNo].lastRoundReward);
_totalAward = _totalAward.add(round_m[_rndNo].exAward);
uint256 _getAward = 0;
//withdraw award
uint256 _totalWithdraw = round_m[_rndNo].eth.mul(51) / 100;
_totalWithdraw = _totalWithdraw.sub(round_m[_rndNo].exAward);
_totalWithdraw = (_totalWithdraw.mul(playerRound_m[_rndNo][msg.sender].keys));
_totalWithdraw = _totalWithdraw / round_m[_rndNo].keys;
uint256 _inveterAmount = playerRound_m[_rndNo][msg.sender].getInveterAmount;
_totalWithdraw = _totalWithdraw.add(_inveterAmount);
uint256 _withdrawed = playerRound_m[_rndNo][msg.sender].withdraw;
if(_totalWithdraw > _withdrawed)
{
_ethOut = _ethOut.add(_totalWithdraw.sub(_withdrawed));
playerRound_m[_rndNo][msg.sender].withdraw = _totalWithdraw;
}
//lastest infect player
if(msg.sender == round_m[_rndNo].infectLastPlayer && round_m[_rndNo].infectLastPlayer != address(0) && round_m[_rndNo].infectiveEndTime != 0)
{
_getAward = _getAward.add(_totalAward.mul(10)/100);
}
if(now > round_m[_rndNo].endTime)
{
// finally award
if(round_m[_rndNo].leader == msg.sender)
{
_getAward = _getAward.add(_totalAward.mul(60)/100);
}
//finally ten person award
for(uint256 i = 0;i < round_m[_rndNo].lastInfective.length; i = i.add(1))
{
if(round_m[_rndNo].lastInfective[i] == msg.sender && (round_m[_rndNo].totalInfective.sub(1) % 11) != i){
if(round_m[_rndNo].infectiveAward_m[i])
continue;
if(round_m[_rndNo].infectLastPlayer != address(0))
{
_getAward = _getAward.add(_totalAward.mul(3)/100);
}
else{
_getAward = _getAward.add(_totalAward.mul(4)/100);
}
round_m[_rndNo].infectiveAward_m[i] = true;
}
}
}
_ethOut = _ethOut.add(_getAward.sub(playerRound_m[_rndNo][msg.sender].hasGetAwardAmount));
playerRound_m[_rndNo][msg.sender].hasGetAwardAmount = _getAward;
if(_ethOut != 0)
{
msg.sender.transfer(_ethOut);
}
// event
emit PlagueEvents.onAward
(
msg.sender,
_rndNo,
_ethOut,
now
);
}
/**
* @dev Get player bonus data
* 0xd982466d
* 0xd982466d0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000028f211f6c07d3b79e0aab886d56333e4027d4f59
* @return player's award
* @return player's can withdraw amount
* @return player's inveter amount
* @return player's has been withdraw
*/
function getPlayerAwardByRndNo(uint256 _rndNo, address _playAddr)
view
public
returns (uint256, uint256, uint256, uint256)
{
require(isStartGame == true, "The game hasn't started yet.");
require(_rndNo <= rndNo, "You're running too fast");
uint256 _ethPlayerAward = 0;
//withdraw award
uint256 _totalWithdraw = round_m[_rndNo].eth.mul(51) / 100;
_totalWithdraw = _totalWithdraw.sub(round_m[_rndNo].exAward);
_totalWithdraw = (_totalWithdraw.mul(playerRound_m[_rndNo][_playAddr].keys));
_totalWithdraw = _totalWithdraw / round_m[_rndNo].keys;
uint256 _totalAward = round_m[_rndNo].eth.mul(30) / 100;
_totalAward = _totalAward.add(round_m[_rndNo].lastRoundReward);
_totalAward = _totalAward.add(round_m[_rndNo].exAward);
//lastest infect player
if(_playAddr == round_m[_rndNo].infectLastPlayer && round_m[_rndNo].infectLastPlayer != address(0) && round_m[_rndNo].infectiveEndTime != 0)
{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(10)/100);
}
if(now > round_m[_rndNo].endTime)
{
// finally award
if(round_m[_rndNo].leader == _playAddr)
{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(60)/100);
}
//finally ten person award
for(uint256 i = 0;i < round_m[_rndNo].lastInfective.length; i = i.add(1))
{
if(round_m[_rndNo].lastInfective[i] == _playAddr && (round_m[_rndNo].totalInfective.sub(1) % 11) != i)
{
if(round_m[_rndNo].infectLastPlayer != address(0))
{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(3)/100);
}
else{
_ethPlayerAward = _ethPlayerAward.add(_totalAward.mul(4)/100);
}
}
}
}
return
(
_ethPlayerAward,
_totalWithdraw,
playerRound_m[_rndNo][_playAddr].getInveterAmount,
playerRound_m[_rndNo][_playAddr].hasGetAwardAmount + playerRound_m[_rndNo][_playAddr].withdraw
);
}
/**
* @dev fee withdraw to receiver, everyone can do it.
* 0x6561e6ba
*/
function feeWithdraw()
onlyHuman()
public
{
require(isStartGame == true, "The game hasn't started yet.");
require(receiver != address(0), "The receiver address has not been initialized.");
uint256 _total = (totalEth.mul(5) / (100));
uint256 _withdrawed = ownerWithdraw;
require(_total > _withdrawed, "No need to withdraw");
ownerWithdraw = _total;
receiver.transfer(_total.sub(_withdrawed));
}
/**
* @dev start game
*/
function startGame()
onlyOwner()
public
{
round_m[1].startTime = now;
round_m[1].endTime = now + rndInfectiveStage_;
round_m[1].lastRoundReward = 0;
isStartGame = true;
}
/**
* @dev change owner.
*/
function changeReceiver(address newReceiver)
onlyOwner()
public
{
receiver = newReceiver;
}
/**
* @dev returns all current round info needed for front end
* 0x747dff42
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256[2], uint256[3], address[2], uint256[6], address[11],address[4])
{
require(isStartGame == true, "The game hasn't started yet.");
uint256 _rndNo = rndNo;
uint256 _totalAwardAtRound = round_m[_rndNo].lastRoundReward.add(round_m[_rndNo].exAward).add(round_m[_rndNo].eth.mul(30) / 100);
return (
_rndNo,
[round_m[_rndNo].eth, round_m[_rndNo].keys],
[round_m[_rndNo].startTime, round_m[_rndNo].endTime, round_m[_rndNo].infectiveEndTime],
[round_m[_rndNo].leader, round_m[_rndNo].infectLastPlayer],
[getBuyPrice(), round_m[_rndNo].lastRoundReward, _totalAwardAtRound, round_m[_rndNo].inveterAmount, round_m[_rndNo].totalInfective % 11, round_m[_rndNo].exAward],
round_m[_rndNo].lastInfective,
round_m[_rndNo].loseInfective
);
}
/**
* @dev return the price buyer will pay for next 1 individual key during first stage.
* 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
require(isStartGame == true, "The game hasn't started yet.");
uint256 _rndNo = rndNo;
uint256 _now = now;
// start next round?
if (_now > round_m[_rndNo].endTime)
{
return (750007031250000);
}
if (round_m[_rndNo].keys < allKeys_)
{
return ((round_m[_rndNo].keys.add(10000000000000000000)).ethRec(10000000000000000000));
}
if(round_m[_rndNo].keys >= allKeys_ &&
round_m[_rndNo].infectiveEndTime != 0 &&
round_m[_rndNo].infectLastPlayer != address(0) &&
_now < round_m[_rndNo].infectiveEndTime)
{
return 5 * 10 ** 16;
}
if(round_m[_rndNo].keys >= allKeys_ && _now > round_m[_rndNo].infectiveEndTime)
{
// increase 0.05 Ether every 3 hours
uint256 currentPrice = (((_now.sub(round_m[_rndNo].infectiveEndTime)) / rndIncreaseTime_).mul(5 * 10 ** 16)).add((5 * 10 ** 16));
return currentPrice;
}
//second stage
return (0);
}
}
library KeysCalc {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
} | * @dev returns all current round info needed for front end 0x747dff42/ | function getCurrentRoundInfo()
public
view
returns(uint256, uint256[2], uint256[3], address[2], uint256[6], address[11],address[4])
{
require(isStartGame == true, "The game hasn't started yet.");
uint256 _rndNo = rndNo;
uint256 _totalAwardAtRound = round_m[_rndNo].lastRoundReward.add(round_m[_rndNo].exAward).add(round_m[_rndNo].eth.mul(30) / 100);
return (
_rndNo,
[round_m[_rndNo].eth, round_m[_rndNo].keys],
[round_m[_rndNo].startTime, round_m[_rndNo].endTime, round_m[_rndNo].infectiveEndTime],
[round_m[_rndNo].leader, round_m[_rndNo].infectLastPlayer],
[getBuyPrice(), round_m[_rndNo].lastRoundReward, _totalAwardAtRound, round_m[_rndNo].inveterAmount, round_m[_rndNo].totalInfective % 11, round_m[_rndNo].exAward],
round_m[_rndNo].lastInfective,
round_m[_rndNo].loseInfective
);
}
| 15,232,307 | [
1,
6154,
777,
783,
3643,
1123,
3577,
364,
6641,
679,
374,
92,
5608,
27,
72,
1403,
9452,
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
]
| [
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,
565,
445,
5175,
11066,
966,
1435,
203,
3639,
1071,
7010,
3639,
1476,
7010,
3639,
1135,
12,
11890,
5034,
16,
2254,
5034,
63,
22,
6487,
2254,
5034,
63,
23,
6487,
1758,
63,
22,
6487,
2254,
5034,
63,
26,
6487,
1758,
63,
2499,
6487,
2867,
63,
24,
5717,
203,
565,
288,
203,
3639,
2583,
12,
291,
1685,
12496,
422,
638,
16,
315,
1986,
7920,
13342,
18642,
5520,
31,
88,
5746,
4671,
1199,
1769,
203,
3639,
2254,
5034,
389,
86,
4880,
2279,
273,
20391,
2279,
31,
203,
3639,
2254,
5034,
389,
4963,
37,
2913,
861,
11066,
273,
3643,
67,
81,
63,
67,
86,
4880,
2279,
8009,
2722,
11066,
17631,
1060,
18,
1289,
12,
2260,
67,
81,
63,
67,
86,
4880,
2279,
8009,
338,
37,
2913,
2934,
1289,
12,
2260,
67,
81,
63,
67,
86,
4880,
2279,
8009,
546,
18,
16411,
12,
5082,
13,
342,
2130,
1769,
203,
540,
203,
3639,
327,
261,
203,
5411,
389,
86,
4880,
2279,
16,
203,
5411,
306,
2260,
67,
81,
63,
67,
86,
4880,
2279,
8009,
546,
16,
3643,
67,
81,
63,
67,
86,
4880,
2279,
8009,
2452,
6487,
203,
5411,
306,
2260,
67,
81,
63,
67,
86,
4880,
2279,
8009,
1937,
950,
16,
3643,
67,
81,
63,
67,
86,
4880,
2279,
8009,
409,
950,
16,
3643,
67,
81,
63,
67,
86,
4880,
2279,
8009,
10625,
386,
688,
25255,
6487,
203,
5411,
306,
2260,
67,
81,
63,
67,
86,
4880,
2279,
8009,
27863,
16,
3643,
67,
81,
63,
67,
86,
4880,
2279,
8009,
10625,
386,
3024,
12148,
6487,
203,
5411,
306,
588,
2
]
|
./full_match/56/0x1C5C0E1B96E7ADDC14AED3688E547A6103A244d9/sources/project_/contracts/Router1.sol | * @dev Set the lottery threshold. @param threshold The lottery threshold./ Update the lottery threshold. | function setLotteryThresHold(
uint256 threshold
) public onlyOwner {
lotteryThreshold = threshold;
}
| 3,227,280 | [
1,
694,
326,
17417,
387,
93,
5573,
18,
225,
5573,
1021,
17417,
387,
93,
5573,
18,
19,
2315,
326,
17417,
387,
93,
5573,
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
]
| [
1,
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,
444,
48,
352,
387,
93,
1315,
455,
20586,
12,
203,
3639,
2254,
5034,
5573,
203,
565,
262,
1071,
1338,
5541,
288,
203,
3639,
17417,
387,
93,
7614,
273,
5573,
31,
203,
565,
289,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity >=0.4.24 <0.6.0;
pragma experimental ABIEncoderV2;
/**
* @title Forum
* @dev Create and manage forum threads and posts
*/
contract forum {
/**
* @dev the name of the forum
*/
string public _forumName;
/**
* @dev the description of the forum
*/
string public _forumDescription;
/**
* @dev the version of the forum. this is used to filter out old incompatible forums when requesting them.
*/
string public _version = "0.0.4";
/**
* @dev represents a single thread
*/
struct FThread {
int id;
string threadName;
string createdBy;
int postCount;
bool isValue;
mapping(int => FPost) posts;
}
/**
* @dev Represents a forum thread without the posts used for getting
* a list of threads
*/
struct FThreadMeta {
int id;
string threadName;
string createdBy;
int postCount;
bool isValue;
}
/**
* @dev represents a single post.
*/
struct FPost {
int id;
string postBody;
string postedBy;
int threadId;
bool isValue;
}
// the number of threads
int _threadCount;
// the owner of the forum
address public owner;
// a mapping of threads to their id.
mapping(int => FThread) public _threads;
/**
* @dev Constructor sets the default value
* @param forumName The name of the forum
* @param forumDescription the description of the forum
*/
constructor(string memory forumName, string memory forumDescription) public {
_forumName = forumName;
_forumDescription = forumDescription;
_threadCount = 0;
owner = msg.sender;
}
/**
* @dev Set the value
* @param forumName The new value
*/
function setName(string memory forumName) public {
_forumName = forumName;
}
/**
* @dev Get the value
*/
function getName() public view returns (string memory forumName) {
return _forumName;
}
/**
* @dev Set the description
* @param forumDescription The new value
*/
function setDescription(string memory forumDescription) public {
_forumDescription = forumDescription;
}
/**
* @dev Get the description
*/
function getDescription() public view returns (string memory forumDescription) {
return _forumDescription;
}
/**
* @dev Gets the forum information as a tuple
*/
function getForumInfo() public view returns (string memory forumName, string memory forumDescription, string memory version) {
return (_forumName, _forumDescription, _version);
}
/**
* @dev Adds a new thread
* @param threadName name of the new thread
* @param createdBy creator of the thread
* @param postBody body of the first post
*/
function addThread(string memory threadName, string memory createdBy, string memory postBody) public {
FThread memory t = FThread(_threadCount, threadName,createdBy, 1, true);
_threads[_threadCount] = t;
FThread storage st = _threads[_threadCount];
if (st.isValue) {
st.posts[0] = FPost(0, postBody,createdBy, _threadCount, true);
}
_threadCount++;
}
/**
* @dev Get the number of threads
*/
function getThreadCount() public view returns (int threadCount) {
return _threadCount;
}
/**
* @dev Get the number of posts in the specified thread.
* @param threadId the id of the thread
*/
function getThreadPostCount(int threadId) public view returns(int postCount) {
return _threads[threadId].postCount;
}
/**
* @dev Gets the thread information for the specified id
* @param id the id of the thread
*/
function getThread(int threadId) public view returns(int id, string memory threadName, string memory createdBy, int postCount) {
if (_threads[threadId].isValue) {
return (_threads[threadId].id, _threads[threadId].threadName, _threads[threadId].createdBy, _threads[threadId].postCount);
} else {
return (-1, "Thread does not exist", "n/a", 0);
}
}
/**
* @dev Add a post to the specified thread
* @param postBody the body of the post
* @param postedBy who created the post
* @param threadId the thread to add the post to
*/
function addPost(string memory postBody, string memory postedBy, int threadId) public {
if (_threads[threadId].isValue) {
FThread storage t = _threads[threadId];
t.posts[t.postCount] = FPost(t.postCount, postBody,postedBy, threadId, true);
t.postCount++;
}
}
/**
* @dev Gets the specific post
* @param threadId the id of the thread to get the post from
* @param postId the id of the post to get
*/
function getPost(int threadId, int postId) public view returns(int id, string memory postBody, string memory postedBy, int ownerId) {
if (_threads[threadId].isValue) {
FThread storage t = _threads[threadId];
if (t.posts[postId].isValue) {
return (t.posts[postId].id, t.posts[postId].postBody, t.posts[postId].postedBy, threadId);
}
}
return (-1, "Post not found in thread", "n/a", -1);
}
/**
* @dev Gets all the posts from a thread
* @param threadId the id of the thread
*/
function getPosts(int threadId) public returns(FPost[] memory posts) {
FThread storage t = _threads[threadId];
FPost[] memory _posts = new FPost[](uint(t.postCount));
for(int256 i = 0; i < int256(t.postCount); i++) {
_posts[uint256(i)] = t.posts[i];
}
return _posts;
}
/**
* @dev Gets all the threads
*/
function getThreads() public returns(FThreadMeta[] memory threads) {
FThreadMeta[] memory retThreads = new FThreadMeta[](uint(_threadCount));
for(int256 i = 0; i < int256(_threadCount); i++) {
FThreadMeta memory meta = FThreadMeta(_threads[i].id, _threads[i].threadName, _threads[i].createdBy, _threads[i].postCount, _threads[i].isValue);
retThreads[uint256(i)] = meta;
}
return retThreads;
}
} | * @dev Set the value @param forumName The new value/ | function setName(string memory forumName) public {
_forumName = forumName;
}
| 967,448 | [
1,
694,
326,
460,
225,
11283,
461,
1021,
394,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
6788,
12,
1080,
3778,
11283,
461,
13,
1071,
288,
203,
3639,
389,
11725,
461,
273,
11283,
461,
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,
-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/0x8F6BA251ad5fd9fF390b10fB92653B61E24C6F98/sources/src/contracts/Ownable_1_0_0.sol | * @dev Contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. By default, the owner account will be the one that deploys the contract. This can later be changed with {transferOwnership}. This module is used through inheritance. It will make available the modifier `onlyOwner`, which can be applied to your functions to restrict their use to the owner./ | abstract contract Ownable is Context {
address private _owner;
address private _contractManager;
event ContractManagerTransferred(
address indexed previousContractManager,
address indexed newContractManager
);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
constructor() {
_transferContractManager(msg.sender);
}
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);
}
function contractManager() public view virtual returns (address) {
return _contractManager;
}
modifier onlyContractManager() {
require(
_msgSender() == _contractManager,
'Ownable: caller is not the contract manager'
);
_;
}
function transferContractManager(
address newContractManager
) public virtual onlyContractManager {
require(
newContractManager != address(0),
'Ownable: new contract owner is the zero address'
);
_transferContractManager(newContractManager);
}
function _transferContractManager(
address newContractManager
) internal virtual {
address oldContractManager = _contractManager;
_contractManager = newContractManager;
emit ContractManagerTransferred(oldContractManager, newContractManager);
}
}
| 15,462,315 | [
1,
8924,
1605,
1492,
8121,
279,
5337,
2006,
3325,
12860,
16,
1625,
1915,
353,
392,
2236,
261,
304,
3410,
13,
716,
848,
506,
17578,
12060,
2006,
358,
2923,
4186,
18,
2525,
805,
16,
326,
3410,
2236,
903,
506,
326,
1245,
716,
5993,
383,
1900,
326,
6835,
18,
1220,
848,
5137,
506,
3550,
598,
288,
13866,
5460,
12565,
5496,
1220,
1605,
353,
1399,
3059,
16334,
18,
2597,
903,
1221,
2319,
326,
9606,
1375,
3700,
5541,
9191,
1492,
848,
506,
6754,
358,
3433,
4186,
358,
13108,
3675,
999,
358,
326,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
17801,
6835,
14223,
6914,
353,
1772,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
565,
1758,
3238,
389,
16351,
1318,
31,
203,
203,
565,
871,
13456,
1318,
1429,
4193,
12,
203,
3639,
1758,
8808,
2416,
8924,
1318,
16,
203,
3639,
1758,
8808,
394,
8924,
1318,
203,
565,
11272,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
203,
3639,
1758,
8808,
2416,
5541,
16,
203,
3639,
1758,
8808,
394,
5541,
203,
565,
11272,
203,
203,
203,
565,
3885,
1435,
288,
203,
3639,
389,
13866,
8924,
1318,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
565,
445,
3410,
1435,
1071,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
389,
8443,
31,
203,
565,
289,
203,
203,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
8443,
1435,
422,
389,
3576,
12021,
9334,
296,
5460,
429,
30,
4894,
353,
486,
326,
3410,
8284,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
1654,
8386,
5460,
12565,
1435,
1071,
5024,
1338,
5541,
288,
203,
3639,
389,
13866,
5460,
12565,
12,
2867,
12,
20,
10019,
203,
565,
289,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
394,
5541,
13,
1071,
5024,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
394,
5541,
480,
1758,
12,
20,
3631,
203,
5411,
296,
5460,
429,
30,
394,
3410,
353,
326,
3634,
1758,
11,
203,
3639,
11272,
203,
3639,
389,
13866,
5460,
12565,
12,
2704,
5541,
1769,
203,
565,
289,
203,
203,
565,
445,
389,
13866,
5460,
12565,
12,
2867,
394,
5541,
2
]
|
pragma solidity ^0.4.18;
/**
* @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;
}
}
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
pragma solidity ^0.4.18;
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
pragma solidity ^0.4.19;
/// @title EtherHiLo
/// @dev the contract than handles the EtherHiLo app
contract EtherHiLo is usingOraclize, Ownable {
uint8 constant NUM_DICE_SIDES = 13;
// settings
uint public rngCallbackGas;
uint public minBet;
uint public maxBetThresholdPct;
bool public gameRunning;
// state
uint public balanceInPlay;
uint public totalGamesPlayed;
uint public totalBetsMade;
uint public totalWinnings;
mapping(address => Game) private gamesInProgress;
mapping(uint => address) private rollIdToGameAddress;
mapping(uint => uint) private failedRolls;
event GameStarted(address indexed player, uint indexed playerGameNumber, uint bet);
event FirstRoll(address indexed player, uint indexed playerGameNumber, uint bet, uint roll);
event DirectionChosen(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, BetDirection direction);
event GameFinished(address indexed player, uint indexed playerGameNumber, uint bet, uint firstRoll, uint finalRoll, uint winnings, uint payout);
event GameError(address indexed player, uint indexed playerGameNumber, uint rollId);
enum BetDirection {
None,
Low,
High
}
// the game object
struct Game {
address player;
BetDirection direction;
uint id;
uint bet;
uint firstRoll;
uint when;
}
// modifier that requires the game is running
modifier gameIsRunning() {
require(gameRunning);
_;
}
// modifier that requires there is a game in progress
// for the player
modifier gameInProgress(address player) {
require(player != address(0));
require(gamesInProgress[player].player != address(0));
_;
}
// modifier that requires there is not a game in progress
// for the player
modifier gameNotInProgress(address player) {
require(player != address(0));
require(gamesInProgress[player].player == address(0));
_;
}
// modifier that requires the caller come from oraclize
modifier onlyOraclize {
require(msg.sender == oraclize_cbAddress());
_;
}
// the constructor
function EtherHiLo() public {
oraclize_setProof(proofType_Ledger);
setRNGCallbackGas(1000000);
setRNGCallbackGasPrice(4000000000 wei);
setMinBet(1 finney);
setGameRunning(true);
setMaxBetThresholdPct(50);
totalGamesPlayed = 0;
totalBetsMade = 0;
totalWinnings = 0;
}
/// Default function
function() external payable {
}
/// =======================
/// EXTERNAL GAME RELATED FUNCTIONS
// begins a game
function beginGame() public payable
gameIsRunning
gameNotInProgress(msg.sender) {
address player = msg.sender;
uint bet = msg.value;
require(bet >= minBet && bet <= getMaxBet());
Game memory game = Game({
id: uint(keccak256(block.number, block.timestamp, player, bet)),
player: player,
bet: bet,
firstRoll: 0,
direction: BetDirection.None,
when: block.timestamp
});
balanceInPlay = balanceInPlay + game.bet;
totalGamesPlayed = totalGamesPlayed + 1;
totalBetsMade = totalBetsMade + game.bet;
gamesInProgress[player] = game;
if (rollDie(player, game.id)) {
GameStarted(player, game.id, bet);
}
}
// finishes a game that is in progress
function finishGame(BetDirection direction) public gameInProgress(msg.sender) {
address player = msg.sender;
require(player != address(0));
require(direction != BetDirection.None);
Game storage game = gamesInProgress[player];
require(game.player != address(0));
game.direction = direction;
gamesInProgress[player] = game;
if (rollDie(player, game.id)) {
DirectionChosen(player, game.id, game.bet, game.firstRoll, direction);
}
}
// determins whether or not the caller is in a game
function getGameState(address player) public view returns
(bool, uint, uint, BetDirection, uint, uint, uint) {
return (
gamesInProgress[player].player != address(0),
gamesInProgress[player].bet,
gamesInProgress[player].firstRoll,
gamesInProgress[player].direction,
gamesInProgress[player].id,
getMinBet(),
getMaxBet()
);
}
// Returns the minimum bet
function getMinBet() public view returns (uint) {
return minBet;
}
// Returns the maximum bet
function getMaxBet() public view returns (uint) {
return SafeMath.div(SafeMath.div(SafeMath.mul(this.balance - balanceInPlay, maxBetThresholdPct), 100), 12);
}
// calculates winnings for the given bet and percent
function calculateWinnings(uint bet, uint percent) public pure returns (uint) {
return SafeMath.div(SafeMath.mul(bet, percent), 100);
}
// Returns the win percent when going low on the given number
function getLowWinPercent(uint number) public pure returns (uint) {
require(number >= 2 && number <= NUM_DICE_SIDES);
if (number == 2) {
return 1200;
} else if (number == 3) {
return 500;
} else if (number == 4) {
return 300;
} else if (number == 5) {
return 300;
} else if (number == 6) {
return 200;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 150;
} else if (number == 9) {
return 140;
} else if (number == 10) {
return 130;
} else if (number == 11) {
return 120;
} else if (number == 12) {
return 110;
} else if (number == 13) {
return 100;
}
}
// Returns the win percent when going high on the given number
function getHighWinPercent(uint number) public pure returns (uint) {
require(number >= 1 && number < NUM_DICE_SIDES);
if (number == 1) {
return 100;
} else if (number == 2) {
return 110;
} else if (number == 3) {
return 120;
} else if (number == 4) {
return 130;
} else if (number == 5) {
return 140;
} else if (number == 6) {
return 150;
} else if (number == 7) {
return 180;
} else if (number == 8) {
return 200;
} else if (number == 9) {
return 300;
} else if (number == 10) {
return 300;
} else if (number == 11) {
return 500;
} else if (number == 12) {
return 1200;
}
}
/// =======================
/// INTERNAL GAME RELATED FUNCTIONS
// process a successful roll
function processDiceRoll(address player, uint roll) private {
Game storage game = gamesInProgress[player];
require(game.player != address(0));
if (game.firstRoll == 0) {
game.firstRoll = roll;
gamesInProgress[player] = game;
FirstRoll(player, game.id, game.bet, game.firstRoll);
return;
}
uint finalRoll = roll;
uint winnings = 0;
if (game.direction == BetDirection.High && finalRoll > game.firstRoll) {
winnings = calculateWinnings(game.bet, getHighWinPercent(game.firstRoll));
} else if (game.direction == BetDirection.Low && finalRoll < game.firstRoll) {
winnings = calculateWinnings(game.bet, getLowWinPercent(game.firstRoll));
}
// this should never happen according to the odds,
// and the fact that we don't allow people to bet
// so large that they can take the whole pot in one
// fell swoop - however, a number of people could
// theoretically all win simultaneously and cause
// this scenario. This will try to at a minimum
// send them back what they bet and then since it
// is recorded on the blockchain we can verify that
// the winnings sent don't match what they should be
// and we can manually send the rest to the player.
uint transferAmount = winnings;
if (transferAmount > this.balance) {
if (game.bet < this.balance) {
transferAmount = game.bet;
} else {
transferAmount = SafeMath.div(SafeMath.mul(this.balance, 90), 100);
}
}
balanceInPlay = balanceInPlay - game.bet;
if (transferAmount > 0) {
game.player.transfer(transferAmount);
}
totalWinnings = totalWinnings + winnings;
GameFinished(player, game.id, game.bet, game.firstRoll, finalRoll, winnings, transferAmount);
delete gamesInProgress[player];
}
// roll the dice for a player
function rollDie(address player, uint gameId) private returns (bool) {
uint N = 7;
uint delay = 0;
bytes32 _queryId = oraclize_newRandomDSQuery(delay, N, rngCallbackGas);
uint rollId = uint(keccak256(_queryId));
// avoid reorgs
if (failedRolls[rollId] == rollId) {
cleanupErrorGame(player, gameId, rollId);
return false;
}
rollIdToGameAddress[rollId] = player;
return true;
}
// called to cleanup an error in a game, usually caused by
// a reorg or other weird blockchain anomoly.
function cleanupErrorGame(address player, uint gameId, uint rollId) private {
Game storage game = gamesInProgress[player];
if (gameId == 0) {
gameId = game.id;
}
if (game.bet > 0) {
game.player.transfer(game.bet);
}
delete gamesInProgress[player];
delete rollIdToGameAddress[rollId];
delete failedRolls[rollId];
GameError(player, gameId, rollId);
}
/// =======================
/// ORACLIZE RELATED FUNCTIONS
// the callback function is called by Oraclize when the result is ready
// the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code:
// the proof validity is fully verified on-chain
function __callback(bytes32 _queryId, string _result, bytes _proof) public onlyOraclize {
uint rollId = uint(keccak256(_queryId));
address player = rollIdToGameAddress[rollId];
// avoid reorgs
if (player == address(0)) {
failedRolls[rollId] = rollId;
return;
}
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
cleanupErrorGame(player, 0, rollId);
} else {
uint randomNumber = (uint(keccak256(_result)) % NUM_DICE_SIDES) + 1;
processDiceRoll(player, randomNumber);
}
delete rollIdToGameAddress[rollId];
}
/// OWNER / MANAGEMENT RELATED FUNCTIONS
// fail safe for balance transfer
function transferBalance(address to, uint amount) public onlyOwner {
to.transfer(amount);
}
// cleans up a player abandoned game, but only if it's
// greater than 24 hours old.
function cleanupAbandonedGame(address player) public onlyOwner {
require(player != address(0));
Game storage game = gamesInProgress[player];
require(game.player != address(0));
uint elapsed = block.timestamp - game.when;
require(elapsed >= 86400);
game.player.transfer(game.bet);
delete gamesInProgress[game.player];
}
// set RNG callback gas
function setRNGCallbackGas(uint gas) public onlyOwner {
rngCallbackGas = gas;
}
// set RNG callback gas
function setRNGCallbackGasPrice(uint price) public onlyOwner {
oraclize_setCustomGasPrice(price);
}
// set the minimum bet
function setMinBet(uint bet) public onlyOwner {
minBet = bet;
}
// set whether or not the game is running
function setGameRunning(bool v) public onlyOwner {
gameRunning = v;
}
// set the max bet threshold percent
function setMaxBetThresholdPct(uint v) public onlyOwner {
maxBetThresholdPct = v;
}
// Transfers the current balance to the owner and terminates the contract.
function destroy() public onlyOwner {
selfdestruct(owner);
}
// Transfers the current balance to the recepient and terminates the contract.
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
} | the callback function is called by Oraclize when the result is ready the oraclize_randomDS_proofVerify modifier prevents an invalid proof to execute this function code: the proof validity is fully verified on-chain avoid reorgs | function __callback(bytes32 _queryId, string _result, bytes _proof) public onlyOraclize {
uint rollId = uint(keccak256(_queryId));
address player = rollIdToGameAddress[rollId];
if (player == address(0)) {
failedRolls[rollId] = rollId;
return;
}
if (oraclize_randomDS_proofVerify__returnCode(_queryId, _result, _proof) != 0) {
cleanupErrorGame(player, 0, rollId);
uint randomNumber = (uint(keccak256(_result)) % NUM_DICE_SIDES) + 1;
processDiceRoll(player, randomNumber);
}
delete rollIdToGameAddress[rollId];
}
| 2,073,426 | [
1,
5787,
1348,
445,
353,
2566,
635,
531,
354,
830,
554,
1347,
326,
563,
353,
5695,
326,
578,
10150,
554,
67,
9188,
3948,
67,
24207,
8097,
9606,
17793,
392,
2057,
14601,
358,
1836,
333,
445,
981,
30,
326,
14601,
13800,
353,
7418,
13808,
603,
17,
5639,
4543,
283,
280,
564,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
1001,
3394,
12,
3890,
1578,
389,
2271,
548,
16,
533,
389,
2088,
16,
1731,
389,
24207,
13,
1071,
1338,
51,
354,
830,
554,
288,
203,
3639,
2254,
5824,
548,
273,
2254,
12,
79,
24410,
581,
5034,
24899,
2271,
548,
10019,
203,
3639,
1758,
7291,
273,
5824,
28803,
12496,
1887,
63,
2693,
548,
15533,
203,
203,
3639,
309,
261,
14872,
422,
1758,
12,
20,
3719,
288,
203,
5411,
2535,
4984,
3251,
63,
2693,
548,
65,
273,
5824,
548,
31,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
309,
261,
280,
10150,
554,
67,
9188,
3948,
67,
24207,
8097,
972,
2463,
1085,
24899,
2271,
548,
16,
389,
2088,
16,
389,
24207,
13,
480,
374,
13,
288,
203,
5411,
6686,
668,
12496,
12,
14872,
16,
374,
16,
5824,
548,
1769,
203,
203,
5411,
2254,
2744,
1854,
273,
261,
11890,
12,
79,
24410,
581,
5034,
24899,
2088,
3719,
738,
9443,
67,
2565,
1441,
67,
30287,
3991,
13,
397,
404,
31,
203,
5411,
1207,
40,
1812,
24194,
12,
14872,
16,
2744,
1854,
1769,
203,
203,
3639,
289,
203,
203,
3639,
1430,
5824,
28803,
12496,
1887,
63,
2693,
548,
15533,
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
]
|
pragma solidity ^0.7.0;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { TokenInterface } from "../../common/interfaces.sol";
import { Helpers } from "./helpers.sol";
import { Events } from "./events.sol";
abstract contract LiquidityManage is Helpers, Events {
/**
* @dev Deposit Liquidity in InstaPool.
* @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param amt token amount.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function deposit(
address token,
uint amt,
uint getId,
uint setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
uint _amt = getUint(getId, amt);
uint ethAmt;
if (token == ethAddr) {
_amt = _amt == uint(-1) ? address(this).balance : _amt;
ethAmt = _amt;
} else {
IERC20 tokenContract = IERC20(token);
_amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt;
tokenContract.approve(address(instaPool), _amt);
}
instaPool.deposit{value: ethAmt}(token, _amt);
setUint(setId, _amt);
_eventName = "LogDepositLiquidity(address,uint256,uint256,uint256)";
_eventParam = abi.encode(token, _amt, getId, setId);
}
/**
* @dev Withdraw Liquidity in InstaPool.
* @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param amt token amount.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function withdraw(
address token,
uint amt,
uint getId,
uint setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
uint _amt = getUint(getId, amt);
instaPool.withdraw(token, _amt);
setUint(setId, _amt);
_eventName = "LogWithdrawLiquidity(address,uint256,uint256,uint256)";
_eventParam = abi.encode(token, _amt, getId, setId);
}
}
abstract contract LiquidityAccessHelper is LiquidityManage {
/**
* @dev Add Fee Amount to borrowed flashloan/
* @param amt Get token amount at this ID from `InstaMemory` Contract.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function addFeeAmount(address token, uint amt, uint getId, uint setId) external payable {
uint _amt = getUint(getId, amt);
require(_amt != 0, "amt-is-0");
uint totalFee = calculateTotalFeeAmt(IERC20(token), _amt);
setUint(setId, totalFee);
}
}
contract LiquidityAccess is LiquidityAccessHelper {
/**
* @dev Access Token Liquidity from InstaPool.
* @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param amt token amount.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function flashBorrow(
address token,
uint amt,
uint getId,
uint setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
uint _amt = getUint(getId, amt);
address[] memory _tknAddrs = new address[](1);
_tknAddrs[0] = token;
uint[] memory _amts = new uint[](1);
_amts[0] = _amt;
instaPool.accessLiquidity(_tknAddrs, _amts);
setUint(setId, _amt);
_eventName = "LogFlashBorrow(address,uint256,uint256,uint256)";
_eventParam = abi.encode(token, _amt, getId, setId);
}
/**
* @dev Return Token Liquidity from InstaPool.
* @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function flashPayback(
address token,
uint getId,
uint setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
uint _amt = instaPool.borrowedToken(token);
IERC20 tokenContract = IERC20(token);
(address feeCollector, uint feeAmt) = calculateFeeAmt(tokenContract, _amt);
address[] memory _tknAddrs = new address[](1);
_tknAddrs[0] = token;
_transfer(payable(address(instaPool)), tokenContract, _amt);
instaPool.returnLiquidity(_tknAddrs);
if (feeAmt > 0) _transfer(payable(feeCollector), tokenContract, feeAmt);
setUint(setId, _amt);
_eventName = "LogFlashPayback(address,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(token, _amt, feeAmt, getId, setId);
}
/**
* @dev Return Token Liquidity from InstaPool and Transfer 20% of Collected Fee to `origin`.
* @param origin origin address to transfer 20% of the collected fee.
* @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function flashPaybackOrigin(
address origin,
address token,
uint getId,
uint setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
require(origin != address(0), "origin-is-address(0)");
uint _amt = instaPool.borrowedToken(token);
IERC20 tokenContract = IERC20(token);
(address feeCollector, uint poolFeeAmt, uint originFeeAmt) = calculateFeeAmtOrigin(tokenContract, _amt);
address[] memory _tknAddrs = new address[](1);
_tknAddrs[0] = token;
_transfer(payable(address(instaPool)), tokenContract, _amt);
instaPool.returnLiquidity(_tknAddrs);
if (poolFeeAmt > 0) {
_transfer(payable(feeCollector), tokenContract, poolFeeAmt);
_transfer(payable(origin), tokenContract, originFeeAmt);
}
setUint(setId, _amt);
_eventName = "LogFlashPaybackOrigin(address,address,uint256,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(origin, token, _amt, poolFeeAmt, originFeeAmt, getId, setId);
}
}
contract LiquidityAccessMulti is LiquidityAccess {
/**
* @dev Access Multiple Token liquidity from InstaPool.
* @param tokens Array of token addresses.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param amts Array of token amount.
* @param getId get token amounts at this IDs from `InstaMemory` Contract.
* @param setId set token amounts at this IDs in `InstaMemory` Contract.
*/
function flashMultiBorrow(
address[] calldata tokens,
uint[] calldata amts,
uint[] calldata getId,
uint[] calldata setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
uint _length = tokens.length;
uint[] memory _amts = new uint[](_length);
for (uint i = 0; i < _length; i++) {
_amts[i] = getUint(getId[i], amts[i]);
}
instaPool.accessLiquidity(tokens, _amts);
for (uint i = 0; i < _length; i++) {
setUint(setId[i], _amts[i]);
}
_eventName = "LogMultiBorrow(address[],uint256[],uint256[],uint256[])";
_eventParam = abi.encode(tokens, amts, getId, setId);
}
/**
* @dev Return Multiple token liquidity from InstaPool.
* @param tokens Array of token addresses.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
* @param getId get token amounts at this IDs from `InstaMemory` Contract.
* @param setId set token amounts at this IDs in `InstaMemory` Contract.
*/
function flashMultiPayback(
address[] calldata tokens,
uint[] calldata getId,
uint[] calldata setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
uint _length = tokens.length;
for (uint i = 0; i < _length; i++) {
uint _amt = instaPool.borrowedToken(tokens[i]);
IERC20 tokenContract = IERC20(tokens[i]);
(address feeCollector, uint feeAmt) = calculateFeeAmt(tokenContract, _amt);
_transfer(payable(address(instaPool)), tokenContract, _amt);
if (feeAmt > 0) _transfer(payable(feeCollector), tokenContract, feeAmt);
setUint(setId[i], _amt);
}
instaPool.returnLiquidity(tokens);
_eventName = "LogMultiPayback(address[],uint256[],uint256[])";
_eventParam = abi.encode(tokens, getId, setId);
}
// TODO - Fix stack too deep
// /**
// * @dev Return Multiple token liquidity from InstaPool and Tranfer 20% of the Fee to Origin.
// * @param tokens Array of token addresses.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
// * @param getId get token amounts at this IDs from `InstaMemory` Contract.
// * @param setId set token amounts at this IDs in `InstaMemory` Contract.
// */
// function flashMultiPaybackOrigin(
// address origin,
// address[] calldata tokens,
// uint[] calldata getId,
// uint[] calldata setId
// ) external payable returns (string memory _eventName, bytes memory _eventParam) {
// uint _length = tokens.length;
// for (uint i = 0; i < _length; i++) {
// uint _amt = instaPool.borrowedToken(tokens[i]);
// IERC20 tokenContract = IERC20(tokens[i]);
// (address feeCollector, uint poolFeeAmt, uint originFeeAmt) = calculateFeeAmtOrigin(tokenContract, _amt);
// _transfer(payable(address(instaPool)), tokenContract, _amt);
// if (poolFeeAmt > 0) {
// _transfer(payable(feeCollector), tokenContract, poolFeeAmt);
// _transfer(payable(origin), tokenContract, originFeeAmt);
// }
// setUint(setId[i], _amt);
// }
// instaPool.returnLiquidity(tokens);
// _eventName = "LogMultiPaybackOrigin(address,address[],uint256[],uint256[])";
// _eventParam = abi.encode(origin, tokens, getId, setId);
// }
}
contract ConnectV2InstaPool is LiquidityAccessMulti {
string public name = "InstaPool-v2";
}
| * @dev Withdraw Liquidity in InstaPool. @param token token address.(For ETH: 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE) @param amt token amount. @param getId Get token amount at this ID from `InstaMemory` Contract. @param setId Set token amount at this ID in `InstaMemory` Contract./ | function withdraw(
address token,
uint amt,
uint getId,
uint setId
) external payable returns (string memory _eventName, bytes memory _eventParam) {
uint _amt = getUint(getId, amt);
instaPool.withdraw(token, _amt);
setUint(setId, _amt);
_eventName = "LogWithdrawLiquidity(address,uint256,uint256,uint256)";
_eventParam = abi.encode(token, _amt, getId, setId);
}
| 13,013,516 | [
1,
1190,
9446,
511,
18988,
24237,
316,
13448,
69,
2864,
18,
225,
1147,
1147,
1758,
18,
12,
1290,
512,
2455,
30,
374,
17432,
1340,
1340,
41,
1340,
73,
41,
73,
41,
1340,
41,
73,
41,
73,
41,
1340,
9383,
41,
1340,
1340,
41,
1340,
1340,
1340,
73,
9383,
73,
41,
13,
225,
25123,
1147,
3844,
18,
225,
2634,
968,
1147,
3844,
622,
333,
1599,
628,
1375,
10773,
69,
6031,
68,
13456,
18,
225,
10446,
1000,
1147,
3844,
622,
333,
1599,
316,
1375,
10773,
69,
6031,
68,
13456,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
598,
9446,
12,
203,
3639,
1758,
1147,
16,
203,
3639,
2254,
25123,
16,
203,
3639,
2254,
2634,
16,
203,
3639,
2254,
10446,
203,
565,
262,
3903,
8843,
429,
1135,
261,
1080,
3778,
389,
2575,
461,
16,
1731,
3778,
389,
2575,
786,
13,
288,
203,
3639,
2254,
389,
301,
88,
273,
336,
5487,
12,
26321,
16,
25123,
1769,
203,
203,
3639,
1804,
69,
2864,
18,
1918,
9446,
12,
2316,
16,
389,
301,
88,
1769,
203,
3639,
444,
5487,
12,
542,
548,
16,
389,
301,
88,
1769,
203,
203,
3639,
389,
2575,
461,
273,
315,
1343,
1190,
9446,
48,
18988,
24237,
12,
2867,
16,
11890,
5034,
16,
11890,
5034,
16,
11890,
5034,
2225,
31,
203,
3639,
389,
2575,
786,
273,
24126,
18,
3015,
12,
2316,
16,
389,
301,
88,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xb17c618ed53B4A3536D2AF3Af73c6b303DbfAb5B/sources/UniswapV3xPYT.sol | @title Oracle library @notice Provides functions to integrate with V3 pool oracle | library OracleLibrary {
function consult(address pool, uint32 secondsAgo)
internal
view
returns (int24 arithmeticMeanTick, uint128 harmonicMeanLiquidity)
{
require(secondsAgo != 0, "BP");
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = secondsAgo;
secondsAgos[1] = 0;
(
int56[] memory tickCumulatives,
uint160[] memory secondsPerLiquidityCumulativeX128s
) = IUniswapV3Pool(pool).observe(secondsAgos);
int56 tickCumulativesDelta = tickCumulatives[1] - tickCumulatives[0];
uint160 secondsPerLiquidityCumulativesDelta = secondsPerLiquidityCumulativeX128s[
1
] - secondsPerLiquidityCumulativeX128s[0];
arithmeticMeanTick = int24(
tickCumulativesDelta / int56(uint56(secondsAgo))
);
if (
tickCumulativesDelta < 0 &&
(tickCumulativesDelta % int56(uint56(secondsAgo)) != 0)
) arithmeticMeanTick--;
uint192 secondsAgoX160 = uint192(secondsAgo) * type(uint160).max;
harmonicMeanLiquidity = uint128(
secondsAgoX160 /
(uint192(secondsPerLiquidityCumulativesDelta) << 32)
);
}
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) internal pure returns (uint256 quoteAmount) {
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
uint256 ratioX128 = FullMath.mulDiv(
sqrtRatioX96,
sqrtRatioX96,
1 << 64
);
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
: FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
}
}
function getQuoteAtTick(
int24 tick,
uint128 baseAmount,
address baseToken,
address quoteToken
) internal pure returns (uint256 quoteAmount) {
uint160 sqrtRatioX96 = TickMath.getSqrtRatioAtTick(tick);
if (sqrtRatioX96 <= type(uint128).max) {
uint256 ratioX192 = uint256(sqrtRatioX96) * sqrtRatioX96;
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX192, baseAmount, 1 << 192)
: FullMath.mulDiv(1 << 192, baseAmount, ratioX192);
uint256 ratioX128 = FullMath.mulDiv(
sqrtRatioX96,
sqrtRatioX96,
1 << 64
);
quoteAmount = baseToken < quoteToken
? FullMath.mulDiv(ratioX128, baseAmount, 1 << 128)
: FullMath.mulDiv(1 << 128, baseAmount, ratioX128);
}
}
} else {
function getOldestObservationSecondsAgo(address pool)
internal
view
returns (uint32 secondsAgo)
{
(
,
,
uint16 observationIndex,
uint16 observationCardinality,
,
,
) = IUniswapV3Pool(pool).slot0();
require(observationCardinality > 0, "NI");
(uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(
pool
).observations((observationIndex + 1) % observationCardinality);
if (!initialized) {
(observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);
}
secondsAgo = uint32(block.timestamp) - observationTimestamp;
}
function getOldestObservationSecondsAgo(address pool)
internal
view
returns (uint32 secondsAgo)
{
(
,
,
uint16 observationIndex,
uint16 observationCardinality,
,
,
) = IUniswapV3Pool(pool).slot0();
require(observationCardinality > 0, "NI");
(uint32 observationTimestamp, , , bool initialized) = IUniswapV3Pool(
pool
).observations((observationIndex + 1) % observationCardinality);
if (!initialized) {
(observationTimestamp, , , ) = IUniswapV3Pool(pool).observations(0);
}
secondsAgo = uint32(block.timestamp) - observationTimestamp;
}
function getBlockStartingTickAndLiquidity(address pool)
internal
view
returns (int24, uint128)
{
(
,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
,
,
) = IUniswapV3Pool(pool).slot0();
require(observationCardinality > 1, "NEO");
(
uint32 observationTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
) = IUniswapV3Pool(pool).observations(observationIndex);
if (observationTimestamp != uint32(block.timestamp)) {
return (tick, IUniswapV3Pool(pool).liquidity());
}
uint256 prevIndex = (uint256(observationIndex) +
observationCardinality -
1) % observationCardinality;
(
uint32 prevObservationTimestamp,
int56 prevTickCumulative,
uint160 prevSecondsPerLiquidityCumulativeX128,
bool prevInitialized
) = IUniswapV3Pool(pool).observations(prevIndex);
require(prevInitialized, "ONI");
uint32 delta = observationTimestamp - prevObservationTimestamp;
tick = int24(
(tickCumulative - prevTickCumulative) / int56(uint56(delta))
);
uint128 liquidity = uint128(
(uint192(delta) * type(uint160).max) /
(uint192(
secondsPerLiquidityCumulativeX128 -
prevSecondsPerLiquidityCumulativeX128
) << 32)
);
return (tick, liquidity);
}
function getBlockStartingTickAndLiquidity(address pool)
internal
view
returns (int24, uint128)
{
(
,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
,
,
) = IUniswapV3Pool(pool).slot0();
require(observationCardinality > 1, "NEO");
(
uint32 observationTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
) = IUniswapV3Pool(pool).observations(observationIndex);
if (observationTimestamp != uint32(block.timestamp)) {
return (tick, IUniswapV3Pool(pool).liquidity());
}
uint256 prevIndex = (uint256(observationIndex) +
observationCardinality -
1) % observationCardinality;
(
uint32 prevObservationTimestamp,
int56 prevTickCumulative,
uint160 prevSecondsPerLiquidityCumulativeX128,
bool prevInitialized
) = IUniswapV3Pool(pool).observations(prevIndex);
require(prevInitialized, "ONI");
uint32 delta = observationTimestamp - prevObservationTimestamp;
tick = int24(
(tickCumulative - prevTickCumulative) / int56(uint56(delta))
);
uint128 liquidity = uint128(
(uint192(delta) * type(uint160).max) /
(uint192(
secondsPerLiquidityCumulativeX128 -
prevSecondsPerLiquidityCumulativeX128
) << 32)
);
return (tick, liquidity);
}
struct WeightedTickData {
int24 tick;
uint128 weight;
}
function getWeightedArithmeticMeanTick(
WeightedTickData[] memory weightedTickData
) internal pure returns (int24 weightedArithmeticMeanTick) {
int256 numerator;
uint256 denominator;
for (uint256 i; i < weightedTickData.length; i++) {
numerator +=
weightedTickData[i].tick *
int256(int128(weightedTickData[i].weight));
denominator += weightedTickData[i].weight;
}
weightedArithmeticMeanTick = int24(numerator / int256(denominator));
weightedArithmeticMeanTick--;
}
function getWeightedArithmeticMeanTick(
WeightedTickData[] memory weightedTickData
) internal pure returns (int24 weightedArithmeticMeanTick) {
int256 numerator;
uint256 denominator;
for (uint256 i; i < weightedTickData.length; i++) {
numerator +=
weightedTickData[i].tick *
int256(int128(weightedTickData[i].weight));
denominator += weightedTickData[i].weight;
}
weightedArithmeticMeanTick = int24(numerator / int256(denominator));
weightedArithmeticMeanTick--;
}
if (numerator < 0 && (numerator % int256(denominator) != 0))
function getChainedPrice(address[] memory tokens, int24[] memory ticks)
internal
pure
returns (int256 syntheticTick)
{
require(tokens.length - 1 == ticks.length, "DL");
for (uint256 i = 1; i <= ticks.length; i++) {
tokens[i - 1] < tokens[i]
? syntheticTick += ticks[i - 1]
: syntheticTick -= ticks[i - 1];
}
}
function getChainedPrice(address[] memory tokens, int24[] memory ticks)
internal
pure
returns (int256 syntheticTick)
{
require(tokens.length - 1 == ticks.length, "DL");
for (uint256 i = 1; i <= ticks.length; i++) {
tokens[i - 1] < tokens[i]
? syntheticTick += ticks[i - 1]
: syntheticTick -= ticks[i - 1];
}
}
}
| 3,680,195 | [
1,
23601,
5313,
225,
28805,
4186,
358,
23367,
598,
776,
23,
2845,
20865,
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,
28544,
9313,
288,
203,
565,
445,
27710,
12,
2867,
2845,
16,
2254,
1578,
3974,
2577,
83,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
1135,
261,
474,
3247,
30828,
15312,
6264,
16,
2254,
10392,
17895,
2586,
335,
15312,
48,
18988,
24237,
13,
203,
565,
288,
203,
3639,
2583,
12,
7572,
2577,
83,
480,
374,
16,
315,
30573,
8863,
203,
203,
3639,
2254,
1578,
8526,
3778,
3974,
2577,
538,
273,
394,
2254,
1578,
8526,
12,
22,
1769,
203,
3639,
3974,
2577,
538,
63,
20,
65,
273,
3974,
2577,
83,
31,
203,
3639,
3974,
2577,
538,
63,
21,
65,
273,
374,
31,
203,
203,
3639,
261,
203,
5411,
509,
4313,
8526,
3778,
4024,
39,
5283,
8785,
16,
203,
5411,
2254,
16874,
8526,
3778,
3974,
2173,
48,
18988,
24237,
39,
11276,
60,
10392,
87,
203,
3639,
262,
273,
467,
984,
291,
91,
438,
58,
23,
2864,
12,
6011,
2934,
12199,
537,
12,
7572,
2577,
538,
1769,
203,
203,
3639,
509,
4313,
4024,
39,
5283,
8785,
9242,
273,
4024,
39,
5283,
8785,
63,
21,
65,
300,
4024,
39,
5283,
8785,
63,
20,
15533,
203,
3639,
2254,
16874,
3974,
2173,
48,
18988,
24237,
39,
5283,
8785,
9242,
273,
3974,
2173,
48,
18988,
24237,
39,
11276,
60,
10392,
87,
63,
203,
7734,
404,
203,
5411,
308,
300,
3974,
2173,
48,
18988,
24237,
39,
11276,
60,
10392,
87,
63,
20,
15533,
203,
203,
3639,
30828,
15312,
6264,
273,
509,
3247,
12,
203,
5411,
4024,
39,
5283,
8785,
9242,
342,
509,
4313,
12,
11890,
4313,
12,
7572,
2577,
83,
3719,
2
]
|
./full_match/3/0x49882825aDA7e758dd2dc4818aBB714D7365D6e5/sources/contracts/faucet0.sol | Our first contract is a faucet! | contract Faucet {
address public me;
pragma solidity 0.6.4;
constructor() public payable {
me = msg.sender;
}
receive() external payable {}
function withdraw(uint withdraw_amount) public {
require(withdraw_amount <= 1000000000000000000);
if(msg.sender==me){
msg.sender;
}
}
function withdraw(uint withdraw_amount) public {
require(withdraw_amount <= 1000000000000000000);
if(msg.sender==me){
msg.sender;
}
}
msg.sender.transfer(withdraw_amount);
} | 8,274,328 | [
1,
51,
295,
1122,
6835,
353,
279,
11087,
5286,
278,
5,
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,
478,
69,
5286,
278,
288,
203,
203,
565,
1758,
1071,
1791,
31,
203,
203,
203,
683,
9454,
18035,
560,
374,
18,
26,
18,
24,
31,
203,
565,
3885,
1435,
1071,
8843,
429,
288,
203,
202,
202,
3501,
273,
1234,
18,
15330,
31,
203,
202,
97,
203,
203,
203,
565,
6798,
1435,
3903,
8843,
429,
2618,
203,
565,
445,
598,
9446,
12,
11890,
598,
9446,
67,
8949,
13,
1071,
288,
203,
3639,
2583,
12,
1918,
9446,
67,
8949,
1648,
2130,
12648,
12648,
1769,
203,
3639,
309,
12,
3576,
18,
15330,
631,
3501,
15329,
203,
5411,
1234,
18,
15330,
31,
203,
3639,
289,
203,
203,
565,
289,
203,
565,
445,
598,
9446,
12,
11890,
598,
9446,
67,
8949,
13,
1071,
288,
203,
3639,
2583,
12,
1918,
9446,
67,
8949,
1648,
2130,
12648,
12648,
1769,
203,
3639,
309,
12,
3576,
18,
15330,
631,
3501,
15329,
203,
5411,
1234,
18,
15330,
31,
203,
3639,
289,
203,
203,
565,
289,
203,
3639,
1234,
18,
15330,
18,
13866,
12,
1918,
9446,
67,
8949,
1769,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
//Simple notary contract to save strings and be able to check later
contract NotaryOffice {
//Actuall mapping of notarized strings which will be saved on blockchain
mapping(bytes32 => bool) private docs;
//Setting the owner of the contract
address private officeOwner;
constructor() public {
//Setting the contract owner on deployment
officeOwner = msg.sender;
}
// ----- Events -----
event Document_Stored(string doc, address docOwner);
event Document_Checked(string doc, address docChecker);
// ----- Modifiers -----
modifier onlyOwner() {
require(
msg.sender == officeOwner,
"Notary Office:Only owner can checkout"
);
_;
}
//Helper function to cast string to bytes and keccak256 hash byte data
function hashDoc(string memory _docToHash) private pure returns (bytes32) {
return keccak256(bytes(_docToHash));
}
// Private function to saved hash data to actuall mapping
function storHashInDocs(bytes32 _documentHash) private {
docs[_documentHash] = true;
}
// ----------- Exposed functions ----------------
// Public function to expose saving string ability
function storeDoc(string memory _docToSave) public payable {
// require 1 ether to save a string
require(
msg.value >= 1 ether,
"Notary Office: We require 1 ether to save a document"
);
emit Document_Stored(_docToSave, msg.sender);
storHashInDocs(hashDoc(_docToSave));
}
// Public function to check for string if it has been saved
function checkDocument(string memory _docToCheck)
public
payable
returns (bool)
{
// require minimum 1 ether for each time checking to be paid
require(
msg.value >= 1 ether,
"Notary Office: We require one ether for our services"
);
emit Document_Checked(_docToCheck, msg.sender);
return docs[hashDoc(_docToCheck)];
}
//checkout public function to get ether back to owner
function checkout() public onlyOwner {
require(
address(this).balance > 1,
"Notary Office:We still havent make that much money"
);
//Setting amount to balance - 1 to already have some balance
uint256 balance = address(this).balance - 1;
msg.sender.transfer(balance);
}
}
| ----- Modifiers ----- | modifier onlyOwner() {
require(
msg.sender == officeOwner,
"Notary Office:Only owner can checkout"
);
_;
}
| 7,243,397 | [
1,
13465,
3431,
3383,
9135,
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
]
| [
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,
0
]
| [
1,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
3397,
1812,
5541,
16,
203,
5411,
315,
1248,
814,
15837,
1812,
30,
3386,
3410,
848,
13926,
6,
203,
3639,
11272,
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
]
|
./partial_match/1/0xD3B1ee664eEDc48C149C9fBd9932CAe0e79Cd968/sources/IykykPass.sol | * the Metadata extension. Built to optimize for lower gas during batch mints. Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). Assumes that an owner cannot have more than 264 - 1 (max value of uint64) of supply. Assumes that the maximum token id cannot exceed 2256 - 1 (max value of uint256)./ Compiler will pack this into a single 256bit word. | contract ERC721A is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
bool burned;
}
struct AddressData {
uint64 balance;
uint64 numberMinted;
uint64 numberBurned;
uint64 aux;
}
uint256 internal _currentIndex;
uint256 internal _burnCounter;
string private _name;
string private _symbol;
mapping(uint256 => TokenOwnership) internal _ownerships;
mapping(address => AddressData) private _addressData;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
function totalSupply() public view returns (uint256) {
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
function totalSupply() public view returns (uint256) {
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
function _totalMinted() internal view returns (uint256) {
unchecked {
return _currentIndex - _startTokenId();
}
}
function _totalMinted() internal view returns (uint256) {
unchecked {
return _currentIndex - _startTokenId();
}
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
function _getAux(address owner) internal view returns (uint64) {
if (owner == address(0)) revert AuxQueryForZeroAddress();
return _addressData[owner].aux;
}
function _setAux(address owner, uint64 aux) internal {
if (owner == address(0)) revert AuxQueryForZeroAddress();
_addressData[owner].aux = aux;
}
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (_startTokenId() <= curr && curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
function ownerOf(uint256 tokenId) public view override returns (address) {
return _ownershipOf(tokenId).addr;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
function _baseURI() internal view virtual returns (string memory) {
return '';
}
function approve(address to, uint256 tokenId) virtual public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
function approve(address to, uint256 tokenId) virtual public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved) public virtual override {
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
function _exists(uint256 tokenId) internal view returns (bool) {
return _startTokenId() <= tokenId && tokenId < _currentIndex &&
!_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
if (_currentIndex != startTokenId) revert();
} else {
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
uint256 end = updatedIndex + quantity;
if (safe && to.isContract()) {
do {
emit Transfer(address(0), to, updatedIndex);
if (!_checkContractOnERC721Received(address(0), to, updatedIndex++, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
} while (updatedIndex != end);
do {
emit Transfer(address(0), to, updatedIndex++);
} while (updatedIndex != end);
}
_currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = _ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
} catch (bytes memory reason) {
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
} else {
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
) internal virtual {}
) internal virtual {}
}
| 4,200,362 | [
1,
5787,
6912,
2710,
18,
27376,
358,
10979,
364,
2612,
16189,
4982,
2581,
312,
28142,
18,
25374,
2734,
87,
854,
695,
6979,
6261,
312,
474,
329,
5023,
622,
389,
1937,
1345,
548,
1435,
261,
7606,
358,
374,
16,
425,
18,
75,
18,
374,
16,
404,
16,
576,
16,
890,
838,
2934,
25374,
716,
392,
3410,
2780,
1240,
1898,
2353,
576,
1105,
300,
404,
261,
1896,
460,
434,
2254,
1105,
13,
434,
14467,
18,
25374,
716,
326,
4207,
1147,
612,
2780,
9943,
576,
5034,
300,
404,
261,
1896,
460,
434,
2254,
5034,
2934,
19,
12972,
903,
2298,
333,
1368,
279,
2202,
8303,
3682,
2076,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
16351,
4232,
39,
27,
5340,
37,
353,
1772,
16,
4232,
39,
28275,
16,
467,
654,
39,
27,
5340,
16,
467,
654,
39,
27,
5340,
2277,
288,
203,
565,
1450,
5267,
364,
1758,
31,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
203,
203,
565,
1958,
3155,
5460,
12565,
288,
203,
3639,
1758,
3091,
31,
203,
3639,
2254,
1105,
787,
4921,
31,
203,
3639,
1426,
18305,
329,
31,
203,
565,
289,
203,
203,
565,
1958,
5267,
751,
288,
203,
3639,
2254,
1105,
11013,
31,
203,
3639,
2254,
1105,
1300,
49,
474,
329,
31,
203,
3639,
2254,
1105,
1300,
38,
321,
329,
31,
203,
3639,
2254,
1105,
9397,
31,
203,
565,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
2254,
5034,
2713,
389,
2972,
1016,
31,
203,
565,
2254,
5034,
2713,
389,
70,
321,
4789,
31,
203,
565,
533,
3238,
389,
529,
31,
203,
565,
533,
3238,
389,
7175,
31,
203,
565,
2874,
12,
11890,
5034,
516,
3155,
5460,
12565,
13,
2713,
389,
995,
12565,
87,
31,
203,
565,
2874,
12,
2867,
516,
5267,
751,
13,
3238,
389,
2867,
751,
31,
203,
565,
2874,
12,
11890,
5034,
516,
1758,
13,
3238,
389,
2316,
12053,
4524,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
565,
3885,
12,
1080,
3778,
508,
67,
16,
533,
3778,
3273,
67,
13,
288,
203,
3639,
389,
529,
273,
508,
67,
31,
203,
3639,
389,
7175,
273,
3273,
67,
31,
203,
3639,
389,
2972,
1016,
2
]
|
pragma solidity 0.5.8;
/// @notice https://eips.ethereum.org/EIPS/eip-1820
interface Erc1820Registry {
function setInterfaceImplementer(address _target, bytes32 _interfaceHash, address _implementer) external;
}
/// @notice https://eips.ethereum.org/EIPS/eip-777
contract Erc777TokensRecipient {
constructor() public {
// keccak256(abi.encodePacked("ERC777TokensRecipient")) == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b
Erc1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24).setInterfaceImplementer(address(this), 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b, address(this));
}
/// @notice called when someone attempts to transfer ERC-777 tokens to this address. If this function were to throw or doesn't exist, then the token transfer would fail.
function tokensReceived(address, address, address, uint256, bytes calldata, bytes calldata) external { }
/// @notice Indicates whether the contract implements the interface `interfaceHash` for the address `_implementer` or not.
/// @param _interfaceHash keccak256 hash of the name of the interface
/// @param _implementer Address for which the contract will implement the interface
/// @return ERC1820_ACCEPT_MAGIC only if the contract implements `interfaceHash` for the address `_implementer`.
function canImplementInterfaceForAddress(bytes32 _interfaceHash, address _implementer) external view returns(bytes32) {
// keccak256(abi.encodePacked("ERC777TokensRecipient")) == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b
if (_implementer == address(this) && _interfaceHash == 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b) {
// keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC")) == 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4
return 0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4;
} else {
return bytes32(0);
}
}
}
/// @notice An Ownable contract is one that has a single address that has elevated control over the contract's operations. Ownership can be transferred between users as a two-step process, one to initiate the transfer and two to receive the transfer. This two-step process ensures that ownership cannot accidentally be given to an address that cannot operate the contract.
contract Ownable {
event OwnershipTransferStarted(address indexed owner, address indexed pendingOwner);
event OwnershipTransferCancelled(address indexed owner, address indexed pendingOwner);
event OwnershipTransferFinished(address indexed oldOwner, address indexed newOwner);
address public owner;
address public pendingOwner;
constructor(address _owner) public {
require(_owner != address(0), "Contract must have an owner.");
owner = _owner;
}
/// @notice a function modifier that ensures the modified function can only be called by the owner of the contract.
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner may call this method.");
_;
}
/// @notice starts the transfer of ownership to a new owner.
/// @param _pendingOwner the address to which ownership should be transferred.
function startOwnershipTransfer(address _pendingOwner) external onlyOwner {
require(_pendingOwner != address(0), "Contract must have an owner.");
// we want to ensure that we get a cancelled or finished event for every ownership transfer, so if a transfer is in progres we first cancel it
if (pendingOwner != address(0)) {
cancelOwnershipTransfer();
}
pendingOwner = _pendingOwner;
emit OwnershipTransferStarted(owner, pendingOwner);
}
/// @notice cancel an in progress ownership transfer.
/// @dev cancellation should not be depended on to cancel a transfer to a malicious address. it's intended purpose is only to cancel transfer to an address that is unable or unwilling to accept the transfer
function cancelOwnershipTransfer() public onlyOwner {
require(pendingOwner != address(0), "There is no pending transfer to be cancelled.");
address _pendingOwner = pendingOwner;
pendingOwner = address(0);
emit OwnershipTransferCancelled(owner, _pendingOwner);
}
/// @notice called by the pending owner as part of the two-step ownership transfer process to accept ownership of the contract.
function acceptOwnership() external {
require(msg.sender == pendingOwner, "Only the pending owner can call this method.");
address _oldOwner = owner;
owner = pendingOwner;
pendingOwner = address(0);
emit OwnershipTransferFinished(_oldOwner, owner);
}
}
/// @notice a smart wallet that is secured against loss of keys by way of backup keys that can be used to recover access with a time delay.
contract RecoverableWallet is Ownable, Erc777TokensRecipient {
event RecoveryAddressAdded(address indexed newRecoverer, uint16 recoveryDelayInDays);
event RecoveryAddressRemoved(address indexed oldRecoverer);
event RecoveryStarted(address indexed newOwner);
event RecoveryCancelled(address indexed oldRecoverer);
event RecoveryFinished(address indexed newPendingOwner);
/// @notice a collection of accounts that are able to recover control of this wallet, mapped to the number of days it takes for each to complete a recovery.
/// @dev the recovery days are also used as a recovery priority, so a recovery address with a lower number of days has a higher recovery priority and can override a lower-priority recovery in progress.
mapping(address => uint16) public recoveryDelaysInDays;
address public activeRecoveryAddress;
uint256 public activeRecoveryEndTime = uint256(-1);
/// @notice the modified function can only be called when the wallet is undergoing recovery.
modifier onlyDuringRecovery() {
require(activeRecoveryAddress != address(0), "This method can only be called during a recovery.");
_;
}
/// @notice the modified function can only be called when the wallet is not undergoing recovery.
modifier onlyOutsideRecovery() {
require(activeRecoveryAddress == address(0), "This method cannot be called during a recovery.");
_;
}
constructor(address _initialOwner) Ownable(_initialOwner) public { }
/// @notice accept ETH transfers into this contract
function () external payable { }
/// @notice add a new recovery address to the wallet with the specified number of day delay
/// @param _newRecoveryAddress the address to be added
/// @param _recoveryDelayInDays the number of days delay between when `_newRecoveryAddress` can initiate a recovery and when it can complete the recovery
function addRecoveryAddress(address _newRecoveryAddress, uint16 _recoveryDelayInDays) external onlyOwner onlyOutsideRecovery {
require(_newRecoveryAddress != address(0), "Recovery address must be supplied.");
require(_recoveryDelayInDays > 0, "Recovery delay must be at least 1 day.");
recoveryDelaysInDays[_newRecoveryAddress] = _recoveryDelayInDays;
emit RecoveryAddressAdded(_newRecoveryAddress, _recoveryDelayInDays);
}
/// @notice removes a recovery address from the collection, preventing it from being able to issue recovery operations in the future
/// @param _oldRecoveryAddress the address to remove from the recovery addresses collection
function removeRecoveryAddress(address _oldRecoveryAddress) public onlyOwner onlyOutsideRecovery {
require(_oldRecoveryAddress != address(0), "Recovery address must be supplied.");
recoveryDelaysInDays[_oldRecoveryAddress] = 0;
emit RecoveryAddressRemoved(_oldRecoveryAddress);
}
/// @notice starts the recovery process. must be called by a previously registered recovery address. recovery will complete in a number of days dependent on the address that initiated the recovery
function startRecovery() external {
uint16 _proposedRecoveryDelayInDays = recoveryDelaysInDays[msg.sender];
require(_proposedRecoveryDelayInDays != 0, "Only designated recovery addresseses can initiate the recovery process.");
bool _inRecovery = activeRecoveryAddress != address(0);
if (_inRecovery) {
// NOTE: the delay for a particular recovery address cannot be changed during recovery nor can addresses be removed during recovery, so we can rely on this being != 0
uint16 _activeRecoveryDelayInDays = recoveryDelaysInDays[activeRecoveryAddress];
require(_proposedRecoveryDelayInDays < _activeRecoveryDelayInDays, "Recovery is already under way and new recovery doesn't have a higher priority.");
emit RecoveryCancelled(activeRecoveryAddress);
}
activeRecoveryAddress = msg.sender;
activeRecoveryEndTime = block.timestamp + _proposedRecoveryDelayInDays * 1 days;
emit RecoveryStarted(msg.sender);
}
/// @notice cancels an active recovery. can only be called by the current contract owner. used to cancel a recovery in case the owner key is found
/// @dev cancellation is only reliable if the recovery time has not elapsed
function cancelRecovery() public onlyOwner onlyDuringRecovery {
address _recoveryAddress = activeRecoveryAddress;
resetRecovery();
emit RecoveryCancelled(_recoveryAddress);
}
/// @notice cancels an active recovery and removes the recovery address from the recoverer collection. used when a recovery key becomes compromised and attempts to initiate a recovery
function cancelRecoveryAndRemoveRecoveryAddress() external onlyOwner onlyDuringRecovery {
address _recoveryAddress = activeRecoveryAddress;
cancelRecovery();
removeRecoveryAddress(_recoveryAddress);
}
/// @notice finishes the recovery process after the necessary delay has elapsed. callable by anyone in case the keys controlling the active recovery address have been lost, since once this is called a new recovery (with a potentially lower recovery priority) can begin.
function finishRecovery() external onlyDuringRecovery {
require(block.timestamp > activeRecoveryEndTime, "You must wait until the recovery delay is over before finishing the recovery.");
address _oldOwner = owner;
owner = activeRecoveryAddress;
resetRecovery();
emit RecoveryFinished(pendingOwner);
emit OwnershipTransferStarted(_oldOwner, owner);
emit OwnershipTransferFinished(_oldOwner, owner);
}
/// @notice deploy a contract from this contract.
/// @dev uses create2, so the address of the deployed contract will be deterministic
/// @param _value the amount of ETH that should be supplied to the contract creation call
/// @param _data the deployment bytecode to execute
/// @param _salt the salt used for deterministic contract creation. see documentation at https://eips.ethereum.org/EIPS/eip-1014 for details on how the address is computed
function deploy(uint256 _value, bytes calldata _data, uint256 _salt) external payable onlyOwner onlyOutsideRecovery returns (address) {
require(address(this).balance >= _value, "Wallet does not have enough funds available to deploy the contract.");
require(_data.length != 0, "Contract deployment must contain bytecode to deploy.");
bytes memory _data2 = _data;
address newContract;
/* solium-disable-next-line */
assembly { newContract := create2(_value, add(_data2, 32), mload(_data2), _salt) }
require(newContract != address(0), "Contract creation returned address 0, indicating failure.");
return newContract;
}
/// @notice executes an arbitrary contract call by this wallet. allows the wallet to send ETH, transfer tokens, use dapps, etc.
/// @param _to contract address to call or send to
/// @param _value the amount of ETH to attach to the call
/// @param _data the calldata to supply to `_to`
/// @dev `_data` is of the same form used to call a contract from the JSON-RPC API, so for Solidity contract calls it is the target function hash followed by the ABI encoded parameters for that function
function execute(address payable _to, uint256 _value, bytes calldata _data) external payable onlyOwner onlyOutsideRecovery returns (bytes memory) {
require(_to != address(0), "Transaction execution must contain a destination. If you meant to deploy a contract, use deploy instead.");
require(address(this).balance >= _value, "Wallet does not have enough funds available to execute the desired transaction.");
(bool _success, bytes memory _result) = _to.call.value(_value)(_data);
require(_success, "Contract execution failed.");
return _result;
}
function resetRecovery() private {
activeRecoveryAddress = address(0);
activeRecoveryEndTime = uint256(-1);
}
}
/// @notice A factory for creating new recoverable wallets. this is useful because an event is fired anytime a wallet is created with this factory, so we can track all wallets created by this by monitoring contract events
contract RecoverableWalletFactory {
event WalletCreated(address indexed owner, RecoverableWallet indexed wallet);
/// @notice creates a new recoverable wallet that is initially owned by the caller
function createWallet() external returns (RecoverableWallet) {
RecoverableWallet wallet = new RecoverableWallet(msg.sender);
emit WalletCreated(msg.sender, wallet);
return wallet;
}
/// @notice this function makes it so one can easily identify whether this contract has been deployed or not. deployment of this factory is done deterministically, so it will live at a well known address on every chain but the user may need to check whether or not this contract has been deployed yet on a given chain
function exists() external pure returns (bytes32) {
return 0x0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef;
}
} | @notice a function modifier that ensures the modified function can only be called by the owner of the contract. | modifier onlyOwner() {
require(msg.sender == owner, "Only the owner may call this method.");
_;
}
| 2,501,231 | [
1,
69,
445,
9606,
716,
11932,
326,
4358,
445,
848,
1338,
506,
2566,
635,
326,
3410,
434,
326,
6835,
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
]
| [
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,
202,
20597,
1338,
5541,
1435,
288,
203,
202,
202,
6528,
12,
3576,
18,
15330,
422,
3410,
16,
315,
3386,
326,
3410,
2026,
745,
333,
707,
1199,
1769,
203,
202,
202,
67,
31,
203,
202,
97,
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
]
|
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: I1INCHGovernance
interface I1INCHGovernance {
function stake(uint256 amount) external;
function unstake(uint256 amount) external;
function balanceOf(address account) external view returns (uint256);
}
// Part: I1INCHGovernanceRewards
interface I1INCHGovernanceRewards {
function earned(address account) external view returns (uint256);
function getReward() external;
}
// 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) {
// 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);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function apiVersion() external pure returns (string memory);
function withdraw(uint256 shares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.3.2";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external virtual view returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external virtual view returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay = 0;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay = 86400; // ~ once a day
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor = 100;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold = 0;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public virtual view returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit - _loss`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCost The keeper's estimated cast cost to call `tend()`.
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCost) public virtual view returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCost` must be priced in terms of `want`.
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/master/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCost The keeper's estimated cast cost to call `harvest()`.
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCost) public virtual view returns (bool) {
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 totalAssets = estimatedTotalAssets();
// NOTE: use the larger of total assets or debt outstanding to book losses properly
(debtPayment, loss) = liquidatePosition(totalAssets > debtOutstanding ? totalAssets : debtOutstanding);
// NOTE: take up any remainder here as profit
if (debtPayment > debtOutstanding) {
profit = debtPayment.sub(debtOutstanding);
debtPayment = debtOutstanding;
}
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by governance or the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
*
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
*/
function protectedTokens() internal virtual view returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// File: Strategy.sol
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
//Initiate 1inch interfaces
I1INCHGovernance public stakeT = I1INCHGovernance(0xA0446D8804611944F1B527eCD37d7dcbE442caba);
I1INCHGovernanceRewards public governanceT = I1INCHGovernanceRewards(0x0F85A912448279111694F4Ba4F85dC641c54b594);
constructor(address _vault) public BaseStrategy(_vault) {
//Approve staking contract to spend 1inch tokens
want.safeApprove(address(stakeT), type(uint256).max);
}
function name() external view override returns (string memory) {
return "Strategy1INCHGovernance";
}
// returns balance of 1INCH
function balanceOfWant() public view returns (uint256) {
return want.balanceOf(address(this));
}
//Returns staked value
function balanceOfStake() public view returns (uint256) {
return stakeT.balanceOf(address(this));
}
function pendingReward() public view returns (uint256) {
return governanceT.earned(address(this));
}
function estimatedTotalAssets() public view override returns (uint256) {
//Add the vault tokens + staked tokens from 1inch governance contract
return balanceOfWant().add(balanceOfStake()).add(pendingReward());
}
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
// We might need to return want to the vault
if (_debtOutstanding > 0) {
uint256 _amountFreed = 0;
(_amountFreed, _loss) = liquidatePosition(_debtOutstanding);
_debtPayment = Math.min(_amountFreed, _debtOutstanding);
}
uint256 balanceOfWantBefore = balanceOfWant();
governanceT.getReward();
_profit = balanceOfWant().sub(balanceOfWantBefore);
}
function adjustPosition(uint256 _debtOutstanding) internal override {
uint256 _wantAvailable = balanceOfWant();
if (_debtOutstanding >= _wantAvailable) {
return;
}
uint256 toInvest = _wantAvailable.sub(_debtOutstanding);
if (toInvest > 0) {
stakeT.stake(toInvest);
}
}
function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) {
// NOTE: Maintain invariant `want.balanceOf(this) >= _liquidatedAmount`
// NOTE: Maintain invariant `_liquidatedAmount + _loss <= _amountNeeded`
uint256 balanceWant = balanceOfWant();
uint256 balanceStaked = balanceOfStake();
if (_amountNeeded > balanceWant) {
// unstake needed amount
stakeT.unstake((Math.min(balanceStaked, _amountNeeded - balanceWant)));
}
// Since we might free more than needed, let's send back the min
_liquidatedAmount = Math.min(balanceOfWant(), _amountNeeded);
}
function prepareMigration(address _newStrategy) internal override {
// If we have pending rewards,take that out
governanceT.getReward();
stakeT.unstake(balanceOfStake());
}
// Override this to add all tokens/tokenized positions this contract manages
// on a *persistent* basis (e.g. not just for swapping back to want ephemerally)
function protectedTokens() internal view override returns (address[] memory) {
address[] memory protected = new address[](1);
protected[0] = address(stakeT); // Staked 1inch tokens from governance contract
return protected;
}
}
| Returns staked value | function balanceOfStake() public view returns (uint256) {
return stakeT.balanceOf(address(this));
}
| 304,181 | [
1,
1356,
384,
9477,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
11013,
951,
510,
911,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
384,
911,
56,
18,
12296,
951,
12,
2867,
12,
2211,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@oni-exchange/onilib/contracts/token/BEP20/SafeBEP20.sol";
import "./IOniProfile.sol";
import "./RobotMintingStation.sol";
/** @title TradingCompV1.
@notice It is a contract for users to collect points
based on off-chain events
*/
contract TradingCompV1 is Ownable {
using SafeBEP20 for IBEP20;
RobotMintingStation public robotMintingStation;
IBEP20 public oniToken;
IOniProfile public oniProfile;
uint256 public constant numberTeams = 3;
uint8 public robotId;
uint256 public winningTeamId; // set to 0 as default
string public tokenURI;
enum CompetitionStatus {Registration, Open, Close, Claiming, Over}
CompetitionStatus public currentStatus;
mapping(address => UserStats) public userTradingStats;
mapping(uint256 => CompetitionRewards) private _rewardCompetitions;
struct CompetitionRewards {
uint256[5] userCampaignId; // campaignId for user increase
uint256[5] oniRewards; // oni rewards per group
uint256[5] pointUsers; // number of points per user
}
struct UserStats {
uint256 rewardGroup; // 0 to 4 --> 4 top / 0: bottom
uint256 teamId; // 1 - 3
bool hasRegistered; // true or false
bool hasClaimed; // true or false
}
event NewCompetitionStatus(CompetitionStatus status);
event TeamRewardsUpdate(uint256 teamId);
event UserRegister(address userAddress, uint256 teamId);
event UserUpdateMultiple(address[] userAddresses, uint256 rewardGroup);
event WinningTeam(uint256 teamId);
/**
* @notice It initializes the contract.
* @param _oniProfileAddress: OniProfile address
* @param _robotStationAddress: RobotMintingStation address
* @param _oniTokenAddress: the address of the ONI token
*/
constructor(
address _oniProfileAddress,
address _robotStationAddress,
address _oniTokenAddress
) public {
oniProfile = IOniProfile(_oniProfileAddress);
robotMintingStation = RobotMintingStation(_robotStationAddress);
oniToken = IBEP20(_oniTokenAddress);
currentStatus = CompetitionStatus.Registration;
}
/**
* @notice It allows users to claim reward after the end of trading competition.
* @dev It is only available during claiming phase
*/
function claimReward() external {
address senderAddress = _msgSender();
require(userTradingStats[senderAddress].hasRegistered, "NOT_REGISTERED");
require(!userTradingStats[senderAddress].hasClaimed, "HAS_CLAIMED");
require(currentStatus == CompetitionStatus.Claiming, "NOT_IN_CLAIMING");
userTradingStats[senderAddress].hasClaimed = true;
uint256 userRewardGroup = userTradingStats[senderAddress].rewardGroup;
uint256 userTeamId = userTradingStats[senderAddress].teamId;
CompetitionRewards memory userRewards = _rewardCompetitions[userTeamId];
if (userRewardGroup > 0) {
oniToken.safeTransfer(senderAddress, userRewards.oniRewards[userRewardGroup]);
if (userTeamId == winningTeamId) {
robotMintingStation.mintCollectible(senderAddress, tokenURI, robotId);
}
}
// User collects points
oniProfile.increaseUserPoints(
senderAddress,
userRewards.pointUsers[userRewardGroup],
userRewards.userCampaignId[userRewardGroup]
);
}
/**
* @notice It allows users to register for trading competition
* @dev Only callable if the user has an active OniProfile.
*/
function register() external {
address senderAddress = _msgSender();
// 1. Checks if user has registered
require(!userTradingStats[senderAddress].hasRegistered, "HAS_REGISTERED");
// 2. Check whether it is joinable
require(currentStatus == CompetitionStatus.Registration, "NOT_IN_REGISTRATION");
// 3. Check if active and records the teamId
uint256 userTeamId;
bool isUserActive;
(, , userTeamId, , , isUserActive) = oniProfile.getUserProfile(senderAddress);
require(isUserActive, "NOT_ACTIVE");
// 4. Write in storage user stats for the registered user
UserStats storage newUserStats = userTradingStats[senderAddress];
newUserStats.teamId = userTeamId;
newUserStats.hasRegistered = true;
emit UserRegister(senderAddress, userTeamId);
}
/**
* @notice It allows the owner to change the competition status
* @dev Only callable by owner.
* @param _status: CompetitionStatus (uint8)
*/
function updateCompetitionStatus(CompetitionStatus _status) external onlyOwner {
require(_status != CompetitionStatus.Registration, "IN_REGISTRATION");
if (_status == CompetitionStatus.Open) {
require(currentStatus == CompetitionStatus.Registration, "NOT_IN_REGISTRATION");
} else if (_status == CompetitionStatus.Close) {
require(currentStatus == CompetitionStatus.Open, "NOT_OPEN");
} else if (_status == CompetitionStatus.Claiming) {
require(winningTeamId > 0, "WINNING_TEAM_NOT_SET");
require(currentStatus == CompetitionStatus.Close, "NOT_CLOSED");
} else {
require(currentStatus == CompetitionStatus.Claiming, "NOT_CLAIMING");
}
currentStatus = _status;
emit NewCompetitionStatus(currentStatus);
}
/**
* @notice It allows the owner to claim the ONI remainder
* @dev Only callable by owner.
* @param _amount: amount of ONI to withdraw (decimals = 18)
*/
function claimRemainder(uint256 _amount) external onlyOwner {
require(currentStatus == CompetitionStatus.Over, "NOT_OVER");
oniToken.safeTransfer(_msgSender(), _amount);
}
/**
* @notice It allows the owner to update team rewards
* @dev Only callable by owner.
* @param _teamId: the teamId
* @param _userCampaignIds: campaignIds for each user group for teamId
* @param _oniRewards: ONI rewards for each user group for teamId
* @param _pointRewards: point to collect for each user group for teamId
*/
function updateTeamRewards(
uint256 _teamId,
uint256[5] calldata _userCampaignIds,
uint256[5] calldata _oniRewards,
uint256[5] calldata _pointRewards
) external onlyOwner {
require(currentStatus == CompetitionStatus.Close, "NOT_CLOSED");
_rewardCompetitions[_teamId].userCampaignId = _userCampaignIds;
_rewardCompetitions[_teamId].oniRewards = _oniRewards;
_rewardCompetitions[_teamId].pointUsers = _pointRewards;
emit TeamRewardsUpdate(_teamId);
}
/**
* @notice It allows the owner to update user statuses
* @dev Only callable by owner. Use with caution!
* @param _addressesToUpdate: the array of addresses
* @param _rewardGroup: the reward group
*/
function updateUserStatusMultiple(address[] calldata _addressesToUpdate, uint256 _rewardGroup) external onlyOwner {
require(currentStatus == CompetitionStatus.Close, "NOT_CLOSED");
require(_rewardGroup <= 4, "TOO_HIGH");
for (uint256 i = 0; i < _addressesToUpdate.length; i++) {
userTradingStats[_addressesToUpdate[i]].rewardGroup = _rewardGroup;
}
emit UserUpdateMultiple(_addressesToUpdate, _rewardGroup);
}
/**
* @notice It allows the owner to set the winning teamId (to collect NFT)
* @dev Only callable by owner.
* @param _winningTeamId: the winning teamId
* @param _tokenURI: the tokenURI
* @param _robotId: the robotId for winners (e.g. 15)
*/
function updateWinningTeamAndTokenURIAndRobotId(
uint256 _winningTeamId,
string calldata _tokenURI,
uint8 _robotId
) external onlyOwner {
require(currentStatus == CompetitionStatus.Close, "NOT_CLOSED");
require((_winningTeamId > 0) && (_winningTeamId <= numberTeams), "NOT_VALID_TEAM_ID");
require(_robotId > 14, "ID_TOO_LOW");
winningTeamId = _winningTeamId;
tokenURI = _tokenURI;
robotId = _robotId;
emit WinningTeam(_winningTeamId);
}
/**
* @notice It checks the claim information
* @dev It does not check if user has a profile since registration required a profile.
* @param _userAddress: the user address
* @return hasRegistered: has the user registered
* @return hasUserClaimed: whether user has claimed
* @return userRewardGroup: the final reward group for each user (i.e. tier)
* @return userOniRewards: the ONI to claim/claimed
* @return userPointReward: the number of points to claim/claimed
* @return canClaimNFT: whether the user gets/got a NFT
*/
function claimInformation(address _userAddress)
external
view
returns (
bool,
bool,
uint256,
uint256,
uint256,
bool
)
{
bool hasUserRegistered = userTradingStats[_userAddress].hasRegistered;
if ((currentStatus != CompetitionStatus.Claiming) && (currentStatus != CompetitionStatus.Over)) {
return (hasUserRegistered, false, 0, 0, 0, false);
} else if (!hasUserRegistered) {
return (hasUserRegistered, false, 0, 0, 0, false);
} else {
uint256 userRewardGroup = userTradingStats[_userAddress].rewardGroup;
uint256 userTeamId = userTradingStats[_userAddress].teamId;
uint256 userOniRewards = _rewardCompetitions[userTeamId].oniRewards[userRewardGroup];
uint256 userPointRewards = _rewardCompetitions[userTeamId].pointUsers[userRewardGroup];
bool hasUserClaimed = userTradingStats[_userAddress].hasClaimed;
bool canClaimNFT;
if ((userTeamId == winningTeamId) && (userRewardGroup > 0)) {
canClaimNFT = true;
}
return (hasUserRegistered, hasUserClaimed, userRewardGroup, userOniRewards, userPointRewards, canClaimNFT);
}
}
/**
* @notice It checks the reward groups for each team
*/
function viewRewardTeams() external view returns (CompetitionRewards[] memory) {
CompetitionRewards[] memory listCompetitionRewards = new CompetitionRewards[](numberTeams);
for (uint256 i = 0; i < numberTeams; i++) {
listCompetitionRewards[i] = _rewardCompetitions[i + 1];
}
return listCompetitionRewards;
}
} | * @notice It allows users to register for trading competition @dev Only callable if the user has an active OniProfile./ 1. Checks if user has registered 2. Check whether it is joinable 3. Check if active and records the teamId 4. Write in storage user stats for the registered user | function register() external {
address senderAddress = _msgSender();
require(!userTradingStats[senderAddress].hasRegistered, "HAS_REGISTERED");
require(currentStatus == CompetitionStatus.Registration, "NOT_IN_REGISTRATION");
uint256 userTeamId;
bool isUserActive;
(, , userTeamId, , , isUserActive) = oniProfile.getUserProfile(senderAddress);
require(isUserActive, "NOT_ACTIVE");
UserStats storage newUserStats = userTradingStats[senderAddress];
newUserStats.teamId = userTeamId;
newUserStats.hasRegistered = true;
emit UserRegister(senderAddress, userTeamId);
}
| 13,006,859 | [
1,
7193,
5360,
3677,
358,
1744,
364,
1284,
7459,
25163,
608,
225,
5098,
4140,
309,
326,
729,
711,
392,
2695,
2755,
77,
4029,
18,
19,
404,
18,
13074,
309,
729,
711,
4104,
576,
18,
2073,
2856,
518,
353,
1233,
429,
890,
18,
2073,
309,
2695,
471,
3853,
326,
5927,
548,
1059,
18,
2598,
316,
2502,
729,
3177,
364,
326,
4104,
729,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
1744,
1435,
3903,
288,
203,
3639,
1758,
5793,
1887,
273,
389,
3576,
12021,
5621,
203,
203,
3639,
2583,
12,
5,
1355,
1609,
7459,
4195,
63,
15330,
1887,
8009,
5332,
10868,
16,
315,
27765,
67,
27511,
2056,
8863,
203,
203,
3639,
2583,
12,
2972,
1482,
422,
5427,
278,
608,
1482,
18,
7843,
16,
315,
4400,
67,
706,
67,
5937,
18643,
2689,
8863,
203,
203,
3639,
2254,
5034,
729,
8689,
548,
31,
203,
3639,
1426,
29302,
3896,
31,
203,
203,
3639,
261,
16,
269,
729,
8689,
548,
16,
269,
269,
29302,
3896,
13,
273,
603,
77,
4029,
18,
588,
1299,
4029,
12,
15330,
1887,
1769,
203,
203,
3639,
2583,
12,
291,
1299,
3896,
16,
315,
4400,
67,
13301,
8863,
203,
203,
3639,
2177,
4195,
2502,
394,
1299,
4195,
273,
729,
1609,
7459,
4195,
63,
15330,
1887,
15533,
203,
3639,
394,
1299,
4195,
18,
10035,
548,
273,
729,
8689,
548,
31,
203,
3639,
394,
1299,
4195,
18,
5332,
10868,
273,
638,
31,
203,
203,
3639,
3626,
2177,
3996,
12,
15330,
1887,
16,
729,
8689,
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
]
|
./full_match/5/0xB385fED7b283F0bc713c19B122E001956121f204/sources/contracts/AutoStake.sol | Functions to be overriden | function redeemAndStake() virtual external returns (uint, uint) {}
| 1,897,020 | [
1,
7503,
358,
506,
31736,
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
]
| [
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,
0
]
| [
1,
565,
445,
283,
24903,
1876,
510,
911,
1435,
5024,
3903,
1135,
261,
11890,
16,
2254,
13,
2618,
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.2;
import "./UserWallet.sol";
/// @title AddressRegistry
/// @notice
/// @dev
contract AddressRegistry {
event LogSetAddress(string name, address addr);
/// @notice Registry of role and address
mapping(bytes32 => address) registry;
/**
* @dev Check if msg.sender is admin or owner.
*/
modifier isAdmin() {
require(
msg.sender == getAddress("admin") ||
msg.sender == getAddress("owner"),
"permission-denied"
);
_;
}
/// @dev Get the address from system registry
/// @param _name (string)
/// @return (address) Returns address based on role
function getAddress(string memory _name) public view returns(address) {
return registry[keccak256(abi.encodePacked(_name))];
}
/// @dev Set new address in system registry
/// @param _name (string) Role name
/// @param _userAddress (string) User Address
function setAddress(string memory _name, address _userAddress) public isAdmin {
registry[keccak256(abi.encodePacked(_name))] = _userAddress;
emit LogSetAddress(_name, _userAddress);
}
}
/// @title LogicRegistry
/// @notice
/// @dev LogicRegistry
contract LogicRegistry is AddressRegistry {
event LogEnableStaticLogic(address logicAddress);
event LogEnableLogic(address logicAddress);
event LogDisableLogic(address logicAddress);
/// @notice Map of static proxy state
mapping(address => bool) public logicProxiesStatic;
/// @notice Map of logic proxy state
mapping(address => bool) public logicProxies;
/// @dev
/// @param _logicAddress (address)
/// @return (bool)
function logic(address _logicAddress) public view returns (bool) {
if (logicProxiesStatic[_logicAddress] || logicProxies[_logicAddress]) {
return true;
}
return false;
}
/// @dev
/// @param _logicAddress (address)
/// @return (bool)
function logicStatic(address _logicAddress) public view returns (bool) {
if (logicProxiesStatic[_logicAddress]) {
return true;
}
return false;
}
/// @dev Sets the static logic proxy to true
/// static proxies mostly contains the logic for withdrawal of assets
/// and can never be false to freely let user withdraw their assets
/// @param _logicAddress (address)
function enableStaticLogic(address _logicAddress) public isAdmin {
logicProxiesStatic[_logicAddress] = true;
emit LogEnableStaticLogic(_logicAddress);
}
/// @dev Enable logic proxy address
/// @param _logicAddress (address)
function enableLogic(address _logicAddress) public isAdmin {
logicProxies[_logicAddress] = true;
emit LogEnableLogic(_logicAddress);
}
/// @dev Disable logic proxy address
/// @param _logicAddress (address)
function disableLogic(address _logicAddress) public isAdmin {
logicProxies[_logicAddress] = false;
emit LogDisableLogic(_logicAddress);
}
}
/**
* @dev Deploys a new proxy instance and sets msg.sender as owner of proxy
*/
contract WalletRegistry is LogicRegistry {
event Created(address indexed sender, address indexed owner, address proxy);
event LogRecord(address indexed currentOwner, address indexed nextOwner, address proxy);
/// @notice Address to UserWallet proxy map
mapping(address => UserWallet) public proxies;
/// @dev Deploys a new proxy instance and sets custom owner of proxy
/// Throws if the owner already have a UserWallet
/// @return proxy ()
function build() public returns (UserWallet proxy) {
proxy = build(msg.sender);
}
/// @dev update the proxy record whenever owner changed on any proxy
/// Throws if msg.sender is not a proxy contract created via this contract
/// @return proxy () UserWallet
function build(address _owner) public returns (UserWallet proxy) {
require(proxies[_owner] == UserWallet(0), "multiple-proxy-per-user-not-allowed");
proxy = new UserWallet();
proxies[address(this)] = proxy; // will be changed via record() in next line execution
proxy.setOwner(_owner);
emit Created(msg.sender, _owner, address(proxy));
}
/// @dev Transafers ownership
/// @param _currentOwner (address) Current Owner
/// @param _nextOwner (address) Next Owner
function record(address _currentOwner, address _nextOwner) public {
require(msg.sender == address(proxies[_currentOwner]), "invalid-proxy-or-owner");
require(proxies[_nextOwner] == UserWallet(0), "multiple-proxy-per-user-not-allowed");
proxies[_nextOwner] = proxies[_currentOwner];
proxies[_currentOwner] = UserWallet(0);
emit LogRecord(_currentOwner, _nextOwner, address(proxies[_nextOwner]));
}
}
/// @title InstaRegistry
/// @dev Initializing Registry
contract InstaRegistry is WalletRegistry {
constructor() public {
registry[keccak256(abi.encodePacked("admin"))] = msg.sender;
registry[keccak256(abi.encodePacked("owner"))] = msg.sender;
}
}
| @title AddressRegistry @notice @dev | contract AddressRegistry {
event LogSetAddress(string name, address addr);
mapping(bytes32 => address) registry;
modifier isAdmin() {
require(
msg.sender == getAddress("admin") ||
msg.sender == getAddress("owner"),
"permission-denied"
);
_;
}
function getAddress(string memory _name) public view returns(address) {
return registry[keccak256(abi.encodePacked(_name))];
}
function setAddress(string memory _name, address _userAddress) public isAdmin {
registry[keccak256(abi.encodePacked(_name))] = _userAddress;
emit LogSetAddress(_name, _userAddress);
}
}
| 5,395,383 | [
1,
1887,
4243,
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,
0
]
| [
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,
0
]
| [
1,
16351,
5267,
4243,
288,
203,
565,
871,
1827,
694,
1887,
12,
1080,
508,
16,
1758,
3091,
1769,
203,
203,
565,
2874,
12,
3890,
1578,
516,
1758,
13,
4023,
31,
203,
203,
565,
9606,
23467,
1435,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
14808,
2932,
3666,
7923,
747,
7010,
5411,
1234,
18,
15330,
422,
14808,
2932,
8443,
6,
3631,
203,
5411,
315,
9827,
17,
13002,
2092,
6,
203,
3639,
11272,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
14808,
12,
1080,
3778,
389,
529,
13,
1071,
1476,
1135,
12,
2867,
13,
288,
203,
3639,
327,
4023,
63,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
529,
3719,
15533,
203,
565,
289,
203,
203,
565,
445,
444,
1887,
12,
1080,
3778,
389,
529,
16,
1758,
389,
1355,
1887,
13,
1071,
23467,
288,
203,
3639,
4023,
63,
79,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
24899,
529,
3719,
65,
273,
389,
1355,
1887,
31,
203,
3639,
3626,
1827,
694,
1887,
24899,
529,
16,
389,
1355,
1887,
1769,
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
]
|
pragma solidity >= 0.4.24;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
address private app;
struct Airline {
uint id;
string name;
bool approved;
bool active;
uint balance;
uint reserved;
uint needed_votes;
uint gained_votes;
}
uint private airline_counter = 0;
mapping(address => Airline) airlines;
mapping(address => mapping(address => bool)) voters_record;
struct Passenger {
address passenger_address;
uint balance;
}
mapping(address => Passenger) passengers;
uint private policies_counter = 0;
struct Insurance {
address holder;
address airline_address;
uint32 flight_id;
uint32 departure_time;
uint cost;
bool claimed;
}
mapping(address => mapping(uint32 => mapping(uint32 => bool))) reservelog;
mapping(uint => Insurance) insurances;
struct Flight {
address airline_address;
uint32 flight_id;
uint32 departure_time;
bool registred;
uint32 status;
}
//airline address => flight no => departure => status
mapping(address => mapping(uint32 => mapping(uint32 => uint32))) flights;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
event AirlineRegistered(address _address, uint id, string name);
event AirlineApproved(address _address, uint id, string name);
event AirlineActivated(address _address, uint id, string name);
event InsuranceBought(uint policy, address holder,address airline,uint32 flight_id, uint32 depature_time, uint price);
event InsuranceClaimed(uint policy, address holder,address airline,uint32 flight_id, uint32 depature_time, uint amount);
event BalanceWithdraw(address holder, uint amount);
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
//enhance the contract protection post deployment to only recive from App
modifier fromAppAdress()
{
require(app == address(0) || msg.sender == app, "Caller is not the linked application");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus
(
bool mode
)
external
requireContractOwner
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(address _from,
string _name,
address _address
)
external
requireIsOperational
fromAppAdress
{
require((airlines[_address].approved == false), "Already registred");
uint _id = airline_counter;
if (airline_counter == 0) {
Airline memory item = Airline(_id, _name, true, false, 0,0,0,0);
airline_counter++;
airlines[_address] = item;
emit AirlineRegistered(_address, _id, _name);
emit AirlineApproved(_address, _id, _name);
} else if (airline_counter > 0 && airline_counter < 4) {
require((airlines[_from].approved == true && airlines[_from].active == true), "This transaction must be done by from an account of an approved and active airline");
Airline memory item2 = Airline(_id, _name, true, false, 0,0,1,1);
airline_counter++;
airlines[_address] = item2;
emit AirlineRegistered(_address, _id, _name);
emit AirlineApproved(_address, _id, _name);
} else if (airline_counter >= 4) {
//require(airlines[msg.sender].approved == true, "This transaction must be done by from an account of an approvedd airline");
require(_address == _from, "Must apply from same account");
uint _needed = ((airline_counter / 2 ) + ( airline_counter % 2 ));
Airline memory item3 = Airline(_id, _name, false, false, 0, 0,_needed,0);
airline_counter++;
airlines[_address] = item3;
emit AirlineRegistered(_address, _id, _name);
}
}
function AirlineStatus
(address _address)
external view
requireIsOperational
fromAppAdress
returns (bool status)
{
return airlines[_address].approved && airlines[_address].active;
}
function approveAirline
(address _from,
address _address)
external
requireIsOperational
fromAppAdress
{
require(airlines[_address].approved == false, "This Airline already got approved");
require(airlines[_from].approved == true && airlines[_from].active == true, "This transaction must be done by from an account of an approvedd airline");
require(voters_record[_address][_from] == false, "This account already approved this airline");
airlines[_address].gained_votes++;
voters_record[_address][_from] = true;
if (airlines[_address].gained_votes == airlines[_address].needed_votes) {
airlines[_address].approved = true;
emit AirlineApproved(_address, airlines[_address].id, airlines[_address].name);
}
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(address _from,
address _airline_address,
uint32 _flight_id,
uint32 _departure_time
)
external
payable
requireIsOperational
fromAppAdress
{
//1000000000000000000
require(flights[_airline_address][_flight_id][_departure_time] == 0, "This flight already have confirmed status");
require(reservelog[_airline_address][_flight_id][_departure_time] == false, "This account already bought an insurance for this flight");
require(msg.value <= 1000000000000000000, "Cannot buy insurance for more than 1 ether (1000000000000000000 wei)");
require(msg.value > 0, "The price must be higher than 0 wei");
require(((uint(msg.value) * uint(3)) / uint(2)) <= (airlines[_airline_address].balance - airlines[_airline_address].reserved), "The request Airline is sold out of insurances");
Insurance memory item = Insurance(_from,_airline_address, _flight_id, _departure_time, msg.value, false);
uint count = policies_counter;
insurances[count] = item;
policies_counter++;
reservelog[_airline_address][_flight_id][_departure_time] = true;
airlines[_airline_address].reserved = airlines[_airline_address].reserved + ((uint(msg.value) * uint(3)) / uint(2));
airlines[_airline_address].balance = airlines[_airline_address].balance + msg.value;
emit InsuranceBought(count,_from,_airline_address,_flight_id,_departure_time,msg.value);
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(address _from,
uint _policy
)
external
requireIsOperational
fromAppAdress
{
require(insurances[_policy].claimed == false, "Policy Already Claimed");
require(insurances[_policy].holder == _from, "Requester is not the Policy Owner");
require(flights[insurances[_policy].airline_address][insurances[_policy].flight_id][insurances[_policy].departure_time] == 20,"The current flight status is not delayed duo to airline failure");
require((airlines[insurances[_policy].airline_address].balance >= ((uint(insurances[_policy].cost) * uint(3)) / uint(2)) && (airlines[insurances[_policy].airline_address].reserved >= ((uint(insurances[_policy].cost) * uint(3)) / uint(2)))),"The airline cannot provide insurance payment at the moment");
insurances[_policy].claimed = true;
airlines[insurances[_policy].airline_address].balance = airlines[insurances[_policy].airline_address].balance - ((uint(insurances[_policy].cost) * uint(3)) / uint(2));
airlines[insurances[_policy].airline_address].reserved = airlines[insurances[_policy].airline_address].reserved - ((uint(insurances[_policy].cost) * uint(3)) / uint(2));
passengers[_from].balance = passengers[_from].balance + ((uint(insurances[_policy].cost) * uint(3)) / uint(2));
emit InsuranceClaimed(_policy,insurances[_policy].holder,insurances[_policy].airline_address,insurances[_policy].flight_id,insurances[_policy].departure_time,((uint(insurances[_policy].cost) * uint(3)) / uint(2)));
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(address _from)
external
requireIsOperational
fromAppAdress
{
require(passengers[_from].balance > 0,"The account balance is currently empty");
uint sum = passengers[_from].balance;
passengers[_from].balance = 0;
address temp = _from;
temp.transfer(sum);
emit BalanceWithdraw(temp,sum);
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(address _from
)
external
payable
requireIsOperational
fromAppAdress
{
require(airlines[_from].approved == true, "funding transaction must be done by from an account of an approved airline");
require(msg.value >= 10000000000000000000, "The Value must be 10 ether more");
//1000000000000000000
airlines[_from].balance = msg.value;
airlines[_from].active = true;
emit AirlineActivated(_from, airlines[_from].id, airlines[_from].name);
}
function setAppAddress (address _app) public requireContractOwner {
app = _app;
}
//airline address => flight no => departure => status
function setFlightStatus (address _airline_address,
uint32 _flight_id,
uint32 _departure_time,
uint32 _status)
external
requireIsOperational
fromAppAdress
{
//sec
flights[_airline_address][_flight_id][_departure_time] = _status;
}
function getFlightStatus (address _airline_address,
uint32 _flight_id,
uint32 _departure_time)
external
view
requireIsOperational
returns (uint32 status)
{
//sec
return flights[_airline_address][_flight_id][_departure_time];
}
/*
function getAirlineInfo (address _address) external requireIsOperational
returns (){
}
*/
/*
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
*/
/**
* @dev Fallback function for funding smart contract.
*
*/
function() public payable
{
//fund();
}
}
| * @dev Initial funding for the insurance. Unless there are too many delayed flights resulting in insurance payouts, the contract should be self-sustaining/1000000000000000000 | function fund
(address _from
)
external
payable
requireIsOperational
fromAppAdress
{
require(airlines[_from].approved == true, "funding transaction must be done by from an account of an approved airline");
require(msg.value >= 10000000000000000000, "The Value must be 10 ether more");
airlines[_from].balance = msg.value;
airlines[_from].active = true;
emit AirlineActivated(_from, airlines[_from].id, airlines[_from].name);
}
| 15,844,856 | [
1,
4435,
22058,
364,
326,
2763,
295,
1359,
18,
1351,
2656,
1915,
854,
4885,
4906,
15278,
1183,
10730,
1377,
8156,
316,
2763,
295,
1359,
293,
2012,
87,
16,
326,
6835,
1410,
506,
365,
17,
87,
641,
3280,
19,
21,
12648,
2787,
9449,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
445,
284,
1074,
203,
18701,
261,
2867,
389,
2080,
203,
18701,
262,
203,
18701,
3903,
203,
18701,
8843,
429,
203,
18701,
2583,
2520,
2988,
287,
203,
18701,
628,
3371,
1871,
663,
203,
565,
288,
203,
3639,
2583,
12,
1826,
3548,
63,
67,
2080,
8009,
25990,
422,
638,
16,
315,
74,
14351,
2492,
1297,
506,
2731,
635,
628,
392,
2236,
434,
392,
20412,
23350,
1369,
8863,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
2130,
12648,
2787,
11706,
16,
315,
1986,
1445,
1297,
506,
1728,
225,
2437,
1898,
8863,
203,
5411,
23350,
3548,
63,
67,
2080,
8009,
12296,
273,
1234,
18,
1132,
31,
203,
5411,
23350,
3548,
63,
67,
2080,
8009,
3535,
273,
638,
31,
203,
5411,
3626,
432,
481,
1369,
28724,
24899,
2080,
16,
225,
23350,
3548,
63,
67,
2080,
8009,
350,
16,
225,
23350,
3548,
63,
67,
2080,
8009,
529,
1769,
203,
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
]
|
./partial_match/1/0x3c9554Cd41290B7e660e2B21f0e815eCF34CE406/sources/DividendsTokenCustomAntiBotLaunchBlockBurnVotes.sol | approve max uint for router approve max int mainLPToken for router exclude charity exclude marketing exclude autoLp exclude tempHolder | {
minTokensBeforeSwap = (1 * 10) ** (decimals() - 1);
uniswapV2Router = _args.uniswapV2Router;
address __weth = _args.uniswapV2Router.WETH();
wrappedNativeAddress = __weth;
uniswapV2Pair = IUniswapV2Factory(_args.uniswapFactory).createPair(
address(this),
_args.mainLPToken
);
isPair[uniswapV2Pair] = true;
mainLPToken = _args.mainLPToken;
weth = __weth;
rewardToken = _args.sameTokenForRewards
? address(this)
: _args.mainLPToken;
isWethRewardToken =
!_args.sameTokenForRewards &&
__weth == _args.mainLPToken;
charityAddress = _args.charityAddress;
marketingAddress = _args.marketingAddress;
autoLiquidityAddress = _args.autoLiquidityAddress;
isExcludedFromFee[owner()] = true;
isExcludedFromFee[address(this)] = true;
isExcludedFromFee[charityAddress] = true;
isExcludedFromFee[marketingAddress] = true;
isExcludedFromFee[address(tempHolder)] = true;
transferTax = _args.transferTaxInfo;
buyTax = _args.buyTaxInfo;
sellTax = _args.sellTaxInfo;
excludedFromRewards[uniswapV2Pair] = true;
excludedFromRewards[address(this)] = true;
excludedFromRewards[address(_args.uniswapV2Router)] = true;
excludedFromRewards[address(tempHolder)] = true;
excludedFromRewards[_owner] = true;
_approve(address(this), address(uniswapV2Router), type(uint256).max);
IERC20(_args.mainLPToken).approve(
address(uniswapV2Router),
type(uint256).max
);
swapTaxes = _args.swapTaxes;
minShareForRewards = _args.minShareForRewards;
sameTokenForRewards = _args.sameTokenForRewards;
_mint(_owner, _initialSupply);
_excludeFromMaxTransaction(uniswapV2Pair, true);
_excludeFromMaxWallet(uniswapV2Pair, true);
_excludeFromMaxTransaction(address(_args.uniswapV2Router), true);
_excludeFromMaxWallet(address(_args.uniswapV2Router), true);
_excludeFromMaxTransaction(_args.charityAddress, true);
_excludeFromMaxWallet(_args.charityAddress, true);
_excludeFromMaxTransaction(_args.marketingAddress, true);
_excludeFromMaxWallet(_args.marketingAddress, true);
_excludeFromMaxTransaction(_args.autoLiquidityAddress, true);
_excludeFromMaxWallet(_args.autoLiquidityAddress, true);
_excludeFromMaxTransaction(address(tempHolder), true);
_excludeFromMaxWallet(address(tempHolder), true);
}
| 2,778,938 | [
1,
12908,
537,
943,
2254,
364,
4633,
6617,
537,
943,
509,
2774,
14461,
1345,
364,
4633,
4433,
1149,
560,
4433,
13667,
310,
4433,
3656,
48,
84,
4433,
1906,
6064,
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
]
| [
1,
1,
1,
1,
1,
1,
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
]
| [
1,
565,
288,
203,
3639,
1131,
5157,
4649,
12521,
273,
261,
21,
380,
1728,
13,
2826,
261,
31734,
1435,
300,
404,
1769,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
1968,
18,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
3639,
1758,
1001,
91,
546,
273,
389,
1968,
18,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
5621,
203,
3639,
5805,
9220,
1887,
273,
1001,
91,
546,
31,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
1968,
18,
318,
291,
91,
438,
1733,
2934,
2640,
4154,
12,
203,
5411,
1758,
12,
2211,
3631,
203,
5411,
389,
1968,
18,
5254,
14461,
1345,
203,
3639,
11272,
203,
3639,
353,
4154,
63,
318,
291,
91,
438,
58,
22,
4154,
65,
273,
638,
31,
203,
203,
3639,
2774,
14461,
1345,
273,
389,
1968,
18,
5254,
14461,
1345,
31,
203,
203,
203,
3639,
341,
546,
273,
1001,
91,
546,
31,
203,
3639,
19890,
1345,
273,
389,
1968,
18,
14307,
1345,
1290,
17631,
14727,
203,
5411,
692,
1758,
12,
2211,
13,
203,
5411,
294,
389,
1968,
18,
5254,
14461,
1345,
31,
203,
3639,
353,
59,
546,
17631,
1060,
1345,
273,
203,
5411,
401,
67,
1968,
18,
14307,
1345,
1290,
17631,
14727,
597,
203,
5411,
1001,
91,
546,
422,
389,
1968,
18,
5254,
14461,
1345,
31,
203,
203,
3639,
1149,
560,
1887,
273,
389,
1968,
18,
3001,
560,
1887,
31,
203,
3639,
13667,
310,
1887,
273,
389,
1968,
18,
3355,
21747,
1887,
31,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol";
/*
Basically this is supposed to be a smart contract that self-regulates masterchef
Inflation is pre-determined with this contract...
It can also be modified "on-chain" by "voting"
1.)WE START AT reward of 25/block
2.) After 22september anyone can call a function that increases rewards(updates masterchef rewards) to 100
called "rapid adoption boost/phase"
3.) Then there are events which anyone can call, on each function call, the reward per block reduces by Golden Ratio(updates to masterchef)
Function can be called:
First every 4 hours (x18)
Then every 6hours (12x)
Then every 8hours (9x)
Then every 12hours (7x)
Then set inflation back to 25/block
Basically what it does is it gives an initial boost to 100/block and reduces it each time period towards 25
4.) on 23rd of November, print like 23.6% of whole supply in 48hours ("big fibonaci payout")
Need to calculate average block time for this.
5.) reduce inflation to 25/block and from there on we are going down per golden ratio on each one
6.) Start "automatic governance"
7.) 3 functions
Initiate and Veto should require an amount of tokens to be "deposited" as a cost for calling the contract and those funds should be burned
//either burned, or just kept by the contract is okay too i guess
Initiate: proposal is pushed into array
Veto: proposal can be voted against(negated)
Execute; if it's not voted against in a period of time, it can be enforced
8.) there are also 3 functions that regulate the rewards for XVMC-USDC, XVMC-WMATIC and DOGE2 pool(poolID 0,1 and 11)
max for doge2 is 5%, and 4% for pool 0 and 1 collectively
has to also be proposed... for each.
8.) When block reward goes to roughly 1.6(it will have to reduce like 15-16times by 1.6 each time from 25 to 1.618),
"The grand fibonaccenning" happens, where supply inflates up to a 1,000,000X
in that time period (creates a total supply of a quadrillion 1,000,000,000,000,000) and sets the
inflation to a golden ratio(in % on annual basis)So basically 1.618% annual inflation.
I think the best way would be to just do a basic exponent function. Basically multiply supply by 1.618X on each event and you
need around 25-30 events. The inflation boost should happen in a period of 7-14 days.
There should be long breaks, and then BIG inflation, rapidly, and then break again(you don't want constant rewards over that period
because if people bought, they would get diluted badly on inflation very quickly).
During those 7-14days, set rewards to 0 for 12hours, then print for 30minutes(until supplies goes x1.618), rest 12hours, repeat,
or something similar...
9.) DO WE NEED TO CREATE PAUSABLE FUNCTION(in autocompounding pool - prevent autocompounding during that period?)
when grand fibonaccening and second is how does 130% work over the long term compounded ??
*/
//how will auto-compounding effect during "Grand Fibonaccening" if one pool receives 1,3x, how does this
// play out during those events where massive amount is printed?
//do we need to add stop auto-compounding durnig those events?
// i don't know solidity, this is just a concept... for the explanation above
/// @notice Owner address
address owner;
int immutable goldenRatio = 1.6180339887 * 1e18; //The golden ratio, the sacred number, do we need e18 or no? WHEN??
int EVMnumberFormat = 1e18;
address immutable ourERCtokenAddress = "0x....."; //our ERC20 token contract address
address immutable deadAddress = "0x000000000000000000000000000000000000dead"; //dead address
int immutable minimum = 1000; //unchangeable, forever min 1000
//can be changed, but not less than minimum. This is the tokens that must be sacrificed in order to "vote"
//voting should be affordable, but a minimum is required to prevent spam
int costToVote = 1000;
//proposals to change costToVote, stored in 2-dimensiona array
proposalMinDeposit[id][[boolean], [firstCallTimestamp], [valueSacrificedForVote], [value]];
//should we set immutable delaybefore enforce like 1day? gives minimum 1 day before proposals can be activated?? HMH idk!
int delayBeforeEnforce = 44000; //minimum number of blocks between when costToVote is proposed and executed
struct proposeDelayBeforeEnforce {
bool valid;
int firstCallTimestamp;
int proposedValue;
}
proposeDelayBeforeEnforcel[] public delayProposals;
boolean gracePeriodActivation = false; //if grace period has been requested
int timestampGracePeriod; //timestamp of grace period
int immutable minThresholdFibonaccening = 1000000;
int thresholdFibonnacening = 5000000;
struct proposalThresholdFibonnacening {
bool valid;
int proposedValue;
int proposedDuration;
int firstCallTimestamp;
}
proposalThresholdFibonnacening[] public proposalThresholdFibonnaceningList; //i don't know syntax for this, is it right?
//delays for Fibonnaccenning Events
int immutable minDelay = 1days; // has to be called minimum 1 day in advance
int immutable maxDelay = 31 days; //1month.. is that good? i think yes
int currentDelay = 3days;
//remember the reward prior to updating so it can be reverted
int rewardPerBlockPriorFibonaccening;
bool eventFibonacceningActive = false; // prevent some functions if event is active ..threshold and durations for fibonaccening
bool expiredGrandFibonaccenning = false;
//fibonacci proposals. When enough penalties are collected, inflation is reduced by golden ratio.
struct fibonaccenningProposal {
bool valid;
int firstCallTimestamp;
int valueSacrificedForVote;
int multiplier;
int currentDelay;
int duration;
}
fibonaccenningProposal[] public fibonaccenningProposalList;
bool handsOff = false;
//by default paused/handsoff is turned on. The inflation should run according to schedule, until after the Big Fibonnaci day
//functions and voting is turned on during that period, immutable
int preProgrammedCounter = 46; //we reduce inflation by golden ratio 35 time
int preProgrammedCounterTimestamp = 0;
bool rapidAdoptionBoost = false; //can only be called once, after 22 september
bool bigFibonaciActivated = false;
bool bigFibonaciStopped = false;
int blocksPerSecond = 2.5;
int durationForCalculation= 12hours; //make this changeable(voteable) BUT NOT WEN COUNTING BLOCKS active!
int lastBlockHeight = 0;
int recordTimeStart;
bool countingBlocks = false;
struct proposalDurationForCalculation {
bool valid;
int duration;
int tokensSacrificedForVoting;
int firstCallTimestamp;
}
proposalDurationForCalculation[] public proposeDurationCalculation;
//need this or not IDK?
int circulatingSupply;
int maximumVoteTokens;
//in case block times change over the long run, this function can be used to rebalance
//only start counting them
int totalFibonaciEventsAfterGrand = 0;
struct proposalRebalanceInflation {
bool valid; //if it remains true, it can be called
int tokensSacrificedForVoting;
int firstCallTimestamp;
}
proposalRebalanceInflation[] public rebalanceProposals;
function initiateRebalanceProposal(int depositingTokensn) {
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if(depositingTokens < costToVote) {"there is a minimum cost to vote"}
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
rebalanceProposals.push("true", depositingTokens, firstCallTimestamp); //submit new proposal
}
//reject if proposal is invalid(false), and if the required delay since last call and first call have not been met
function executeRebalanceProposal(int proposalID) {
if(rebalanceProposals[proposalID][0] == false || proposeDurationCalculation[proposalID][2] < (block.timestamp + delayBeforeEnforce)) { reject }
rebalanceInflation(proposalID);
rebalanceProposals[proposalID][0] = false;
}
function vetoRebalanceProposal(int proposalID, int depositingTokens) {
if (rebalanceProposals[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != rebalanceProposals[proposalID][1]) { reject "must match amount to veto"; }
rebalanceProposals[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//there should be valid proposalID to do so tbh
//this rebalances inflation to Golden ratio(and number of fibonacennings afterward)
function rebalanceInflation(int proposalID) {
if(totalFibonaciEventsAfterGrand == 0) { reject "only works after grand fibonaccening" }
if(!rebalanceProposals[proposalID][0]) { reject "proposal is invalid" }
//rebalance inflation to
setInflation(getTotalSupply() * (((100 - goldenRatio)/100)exponent totalFibonaciEventsAfterGrand));
}
//can't use more than 0.1% of circulating supply to vote, making sure to prevent tyranny and always potentially veto
//US presidentials cost approximately 0.0133% of total US worth. This is crypto so let's give little more space
//in all proposals you can't deposit more than this amount of tokens
function updateMaximumVoteTokens {
maximumVoteTokens = getTotalSupply() * 0.0005;
}
function updateCirculatingSupply(){
circulatingSupply = getTotalSupply();
}
//after counting is done, updated into database the numberino
function calculateAverageBlockTime() {
if(countingBlocks && (recordTimeStart + durationForCalculation) >= block.timestamp) {
blocksPerSecond = (block.height - lastBlockHeight) / durationForCalculation(must be in seconds); //gets number of blocks per second
countingBlocks = false;
}
}
//can be called by anybody because it doesn't have any real impact
function startCountingBlocks(){
require(!countingBlocks) { "already counting blocks" }
countingBlocks = true;
lastBlockHeight = block.height; //remember block number height
recordTimeStart = block.time; //remember time
}
//shit doesn't really matter cuz after big fibonnaci daz we go down to 25-golden ratio, so need not to remember until then
function rapidAdoptionBoost() public {
if(rapidAdoptionBoost) { reject "already been activated"; }
if(block.timestamp < 22.september) { reject "rapidAdoptionBoost can only be activated after this period" }
rapidAdoptionBoost = true;
}
function updatePreProgrammedRewards() public anyone1 can call {
if(!rapidAdoptionBoost) { reject "programIsOff"; } //not sure which one is the right one now
if(preProgrammedCounter == 46) {
setInflation(100 * EVMnumberFormat);
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
}
if(lastPreProgrammedCounter < 46 && lastPreProgrammedCounter > 27) {
if(preProgrammedCounterTimestamp + 5760 < block.timestamp) { reject "delay not met, must wait 4hrs"; }
rewardPerBlockPriorFibonaccening -= goldenRatio;
setInflation(rewardPerBlockPriorFibonaccening);
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
}
if(lastPreProgrammedCounter < 28 && lastPreProgrammedCounter > 14) {
if(preProgrammedCounterTimestamp + 8640 < block.timestamp) { reject "delay not met, must wait 6hrs"; }
rewardPerBlockPriorFibonaccening -= goldenRatio;
setInflation(rewardPerBlockPriorFibonaccening);
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
}
if(lastPreProgrammedCounter < 15 && lastPreProgrammedCounter > 4) {
if(preProgrammedCounterTimestamp + 11520 < block.timestamp) { reject "delay not met, must wait 8hrs"; }
rewardPerBlockPriorFibonaccening -= goldenRatio;
setInflation(rewardPerBlockPriorFibonaccening);
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
}
if(lastPreProgrammedCounter < 5 && lastPreProgrammedCounter > 1) {
if(preProgrammedCounterTimestamp + 8640 < block.timestamp) { reject "delay not met, must wait 12hrs"; }
rewardPerBlockPriorFibonaccening -= goldenRatio;
setInflation(rewardPerBlockPriorFibonaccening);
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
}
if(lastPreProgrammedCounter == 1) {
if(preProgrammedCounterTimestamp + 17280 < block.timestamp) { reject "delay not met, must wait 1day"; }
rewardPerBlockPriorFibonaccening -= goldenRatio;
setInflation(25000000000000000000); // set to 25XVMC/block
preProgrammedCounter--; //deduct by 1
preProgrammedCounterTimestamp = time.block;
//inflation goes to 25XVMC block, rapidadoption boost can't be activated ever again and the counter can't go above 0 again either
}
}
//Big fibonnaci day, 23.8% of supply printed in a period of 48hours, then revert to 25XVMC/block and on-chain governance
//anyone can call this
function bigFibonaciPayout() {
//function can be called 12hours prior to the day UTC, and expires 12hours after, total 48hours duration
if(!bigFibonaciActivated && block.timestamp >(12hourspprior23november)) { //activate big fibonaci day
bigFibonaciActivated = true;
//calculate rewards, need a function that gets blocks
setInflation((getTotalSupply()*0.236) / (48 * 3600 / blocksPerSecond));
// 23.6% of total supply must be printed in 48hours,s o reward per second should be totalsupply*0.236 / 48hoursinseconds
//halt other functions as to not mess up? IDK!!
}
}
bool endBigFibonaciDay = false;
function endBigFibonaciPayout() {
require(bigFibonaciActivated && !endBigFibonaciDay) { "can't activated if not ongoing" })
require(block.timestamp > 12hoursafter23november) { "must last 24hours" }
//must be active and must expire and must not be callable again function
setInflation(25000000000000000000); // set to 25tokens/block
rewardPerBlockPriorFibonaccening = 25000000000000000000;
endBigFibonaciDay = true;
}
struct proposalFarm {
bool valid;
int poolid;
int newAllocation;
int tokensSacrificedForVoting;
int firstCallTimestamp;
}
proposalFarm[] public proposalFarmUpdate;
function initiateFarmProposal(int depositingTokens, int poolid, int newAllocation[]) {
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if(depositingTokens < costToVote) {"there is a minimum cost to vote"}
if(poolid !(in_array([0,1,11]))) { "reject, only allowed for these pools" }
if(poolid == 11 && newAllocation > 5000) { reject "max 5k" }
//you can propose any amount but it will not get accepted by updateFarms anyways
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
proposalFarmUpdate.push("true", poolid, newAllocation, depositingTokens, firstCallTimestamp); //submit new proposal
}
function vetoFarmProposal(int proposalID, int depositingTokens) {
if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != proposalFarmUpdate[proposalID][3]) { reject "must match amount to veto"; }
proposalFarmUpdate[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//updateFarms actually acts akin to the execute Proposal in this case
//this is to update farm and pool allocations,which can be proposed
int allocationPool1 = XX; //SET THIS AT BEGINNING
int allocationPool2 = XX;
int immutable maxFarmRewards = 1000; //idk the actual number, set this shit broski..but this is not locked so welp fuck
function updateFarm0(int proposalID, int massUpdate) {
if(proposalFarmUpdate[proposalID][0] = "false"( { reject "not valid proposal"})
if(proposalFarmUpdate[proposalID][3] + delayBeforeEnforce > block.timestamp) {reject " not valid yet"}
if(allocationPool2 + proposalFarmUpdate[proposalID][2] > maxFarmRewards) { reject "exceeding max" }
updatePool(0, newAllocationPool1, massUpdate);;
}
function updateFarm1(int proposalID, int massUpdate) {
if(proposalFarmUpdate[proposalID][0] = "false"( { reject "not valid proposal"})
if(proposalFarmUpdate[proposalID][3] + delayBeforeEnforce > block.timestamp) {reject " not valid yet"}
if(allocationPool1 + proposalFarmUpdate[proposalID][2] > maxFarmRewards) { reject "exceeding max" }
updatePool(1, newAllocationPool2, massUpdate);
}
//poolid preset to 11
function updateFarm11(int massUpdate, int proposalID) {
if(proposalFarmUpdate[proposalID][0] = "false"( { rject "not valid proposal"})
if(proposalFarmUpdate[proposalID][3] + delayBeforeEnforce > block.timestamp) {reject " not valid yet"}
//need proposal
updatePool(11, newAllocation, massUpdate);
}
function initiateDelayProposal(int depositingTokens, int duration) {
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if(depositingTokens < costToVote) {"there is a minimum cost to vote"}
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
proposeDurationCalculation.push("true", duration, depositingTokens, firstCallTimestamp); //submit new proposal
}
//reject if proposal is invalid(false), and if the required delay since last call and first call have not been met
function executeDelayProposal(int proposalID) {
if(proposeDurationCalculation[proposalID][0] == false || proposeDurationCalculation[proposalID][3] < (block.timestamp + delayBeforeEnforce)) { reject }
durationForCalculation = proposeDurationCalculation[proposalID][1]; // enforce new rule
proposeDurationCalculation[proposalID][0] = false; //expire the proposal, can't call it again.. no way to make it true again, however it can be resubmitted(and vettod too)
}
function vetoDelayProposal(int proposalID, int depositingTokens) {
if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != proposeDurationCalculation[proposalID][2]) { reject "must match amount to veto"; }
proposeDurationCalculation[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
function initiateProposalDurationForCalculation(int depositingTokens, int duration) {
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if(depositingTokens < costToVote) {"there is a minimum cost to vote"}
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
proposeDurationCalculation.push("true", duration, depositingTokens, firstCallTimestamp); //submit new proposal
}
//reject if proposal is invalid(false), and if the required delay since last call and first call have not been met
function executeProposalDurationForCalculation(int proposalID) {
if(proposeDurationCalculation[proposalID][0] == false || proposeDurationCalculation[proposalID][3] < (block.timestamp + delayBeforeEnforce)) { reject }
durationForCalculation = proposeDurationCalculation[proposalID][1]; // enforce new rule
proposeDurationCalculation[proposalID][0] = false; //expire the proposal, can't call it again.. no way to make it true again, however it can be resubmitted(and vettod too)
}
function vetoProposalDurationForCalculation(int proposalID, int depositingTokens) {
if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != proposeDurationCalculation[proposalID][2]) { reject "must match amount to veto"; }
proposeDurationCalculation[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//fibonaccenning function determines by how much the reward per block is reduced
//prior to the "grand fibonaccenning" event, the reward per block is deducted by the golden ratio
//on the big event, reward per block is set to the golden ratio (totalsupply * 0.01618) AKA 1.6180%/ANNUALLY
//after the big event, reward per block is reduced by a golden number in percentage = (previous * ((100-1.6180)/100))
function calculateFibonaccenningNewRewardPerBlock() {
if(expiredGrandFibonaccenning == false) {
return rewardPerBlockPriorFibonaccening - goldenRatio; //reduce reward by golden ratio(subtract)
} else {
return rewardPerBlockPriorFibonaccening * ((100 * EVMnumberFormat - goldenRatio)/100 * EVMnumberFormat); //reduce by a goldenth ratio of a percenth (multiply by) ....
}
}
//gets total(circulating) supply for XVMC token(deducting from dead address and thhis smart contract that holds penalties)
function getTotalSupply() {
return IERC20(ourERCtokenAddress).totalSupply() - ERC20(ourERCtokenAddress).balanceOf(this) - ERC20(ourERCtokenAddress).balanceOf(deadAddress);
}
//TO-DO PREVENT CALLING OF MOST FUNCTIONS WHEN GRAND FIBONNACENING IS ACTIVE!!! (freeze funciton..perhaps should be during several things)
function InitiateSetMinDeposit(int depositingTokens, int number) {
if(number < minimum) { reject "immutable minimum 1000tokens" }
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if (number < costToVote) {
if (depositingTokens != costToVote) { reject "costs to vote" }
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
proposalMinDeposit.push("true", block.timestamp, depositingTokens, number); //submit new proposal
} else {
if (depositingTokens != number) { reject "must deposit as many tokens as new minimum will be" }
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
proposalMinDeposit.push("true", block.timestamp, 0, number); //submit new proposal
}
}
//reject if proposal is invalid(false), and if the required delay since last call and first call have not been met
function executeSetMinDeposit(int proposalID) {
if(proposalMinDeposit[proposalID][0] == false || proposalMinDeposit[proposalID][1] < (block.timestamp + delayBeforeEnforce) || proposalMinDeposit[proposalID][2] < (block.timestamp + delayBeforeLastCall)) { reject }
costToVote = proposalMinDeposit[proposalID][3]; //update the costToVote according to proposed value
proposalMinDeposit[proposalID][0] = false; //expire the proposal, can't call it again.. no way to make it true again, however it can be resubmitted(and vettod too)
}
function vetoSetMinDeposit(int proposalID, int depositingTokens) {
if (proposalMinDeposit[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != proposalMinDeposit[proposalID][2]) { reject "must match amount to veto"; }
proposalMinDeposit[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
function getCurrentInflation() {
return get value From Another Contract("XVMCPerBlock", contractAddress) // get value for reward per block from masterchef contract
}
//this can only be called by this smart contract(the rebalancePools function)
function updatePool(int poolID, int allocation, bool massUpdate) {
//call the set contract in masterchef
if(poolID != in_array(1,2,3,4,5)) { reject "only can update pre-set poolIDs" } //can only modify pools with certain ID
//if only contract can call then it doesn't really matter, can call them all
{outsidecontractCall-Masterchef} set(poolID, allocation, 0, massUpdate); //set parameters - call function set in Masterchef
}
//can be called anybody, calls maddupdatepools funciton in masterchef
function massUpdatePools() {
{outsidecontractCall-Masterchef} massUpdatePools(); //call massUpdatePools in masterchef
}
//autocompounding pool addresses...
address public pool1 = "0x...";
address public pool2 = "";
address public pool3 = "";
address public pool4 = "";
address public pool5 = "";
address public pool6 = "";
//called by this smart contract only
function calculateShare(int total, int poolshare, int multiplier) {
return ((total /poolshare) * multiplier); //calculate
}
//can be called by anybody, basically re-calculate all the amounts in pools and update pool shares into masterchef
function rebalancePools() {
//get balance for each pool
int balancePool1 = IERC20(pool1).totalSupply();
int balancePool2 = IERC20(pool2).totalSupply();
int balancePool3 = IERC20(pool3).totalSupply();
int balancePool4 = IERC20(pool4).totalSupply();
int balancePool5 = IERC20(pool5).totalSupply();
int balancePool6 = IERC20(pool6).totalSupply();
int total = balancePool1 + balancePool2 + balancePool3 + balancePool4 + balancePool5 + balancePool6;
//have to change first value(replace 0 with pool ID)...find pool ids in masterchef once you deploy autocompounding pools
//call update function that calls the masterchef and updates values
updatePool(0, calculateShare(total, balancePool1, 10), 0);
updatePool(0, calculateShare(total, balancePool2, 30), 0);
updatePool(0, calculateShare(total, balancePool3, 45), 0);
updatePool(0, calculateShare(total, balancePool4, 100), 0);
updatePool(0, calculateShare(total, balancePool5, 115), 0);
updatePool(0, calculateShare(total, balancePool6, 130), 1); //mass update pools on the last one? i think
}
//can only be called by the contract itself IMPORTANT.. only functions of hte smart contract can call this!!
function setInflation(int rewardPerBlock) {
{outsidecontractCall-Masterchef} updateEmissionRate(rewardPerBlock);
//do we need to remember previous reward? IDK!
//add here if needed (not needed??)
rewardPerBlockPriorFibonaccening = rewardPerBlock; //remember new reward as current ?? IDK
}
//call proposal for minimum amount collected for fibonacenning event
//can be called by anbody
function proposeSetMinThresholdFibonaccenning(int depositingTokens, int newMinimum) {
if(newMinimum < minThresholdFibonaccening) { rejecc "cant go lower than 0.1"}
if(depositingTokens < costToVote) { reject "minimum threshold to vote not met";}
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
proposalThresholdFibonnacening.push("true", block.timestamp, newMinimum); //submit new proposal
}
function vetoSetMinThresholdFibonaccenning(int proposalID, int depositingTokens) {
if (proposalThresholdFibonnacening[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != costToVote) { reject "it costs to vote"; }
proposalThresholdFibonnacening[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//enforce function
function executeSetMinThresholdFibonaccenning(int proposalID) {
if(proposalThresholdFibonnacening[proposalID][0] == false || proposalThresholdFibonnacening[proposalID][1] < (block.timestamp + delayBeforeEnforce)) { reject }
thresholdFibonnacening = proposalThresholdFibonnacening[proposalID][2]; //update the threshold to the proposed value
proposalThresholdFibonnacening[proposalID][0] = false; //expire the proposal - prevent it from being called again
}
//should this be vettoable? IDK
//do we even need this... i don't think so because it is included in the fibonacci proposal itself..i think this function below is useless
function setDelay (int depositing tokens, int delay) {
if(delay > maxDelay || delay < minDelay) { reject "not allowed" }
if(depositingTokens != costToVote) { reject "it costs to vote"; }
currentDelay = delay; //make sure as not to confuse days, hours, blocks,... idk how
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//basically this is a "compensation" for re-distributing the penalties
//period of boosted inflation, and after it ends, global inflation reduces
function proposeFibonaccenning(int depositingTokens, int multiplier, int delay, int duration) {
if(depositingTokens != costToVote || ) { reject "costs to submit decisions" }
if(ERC20(putiheretokenaddress).balanceOf(this) < thresholdFibonnacening) { reject "need to collect penalties before calling"; }
if(delay != currentDelay) { reject "respect current delay setting" }
if(eventFibonacceningActive == true) { reject "fibonaccening already activated" }
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
//after it's approved, changing some things should be PAUSED..add this
//this has to be vettoable for sure
//propose new fibonaccening event
fibonaccenningProposal.push(true, block.timestamp, depositingTokens, multiplier, delay, duration)
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
//need to add safeguard so that multiplier*duration does not exceed XXX of amount or something
//must also be able to prevent multiple fibonaccis to be done... perhaps can't submit new proposal IF last one is true
//this might be a global problem though(need to do this on all functions..prevent proposals if one is active already??)
//safeguard is that you need to burn the tokens to execute fibonaccening
}
function vetoFibonaccenning(int proposalID, int depositingTokens) {
if(depositingTokens != costToVote) { reject "costs to vote" }
if(fibonaccenningProposal[proposalID][0] == false) { reject "proposal already vettod" }
fibonaccenningProposal[proposalID][0] = false; //negates proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//there is fibonacenning PRIOR to grandFibonacenningEvent and after it
//the only difference is prior it reduces inflation(subtracts) and afterwards it multiplies by ((100-1.618)/100)
//this is included in the function to setInflation already??
function leverPullFibonaccenningLFG(proposalID) {
//not sure if this is neccessary since the lever should never be pulled if this condition not met
if(ERC20(putiheretokenaddress).balanceOf(this) < thresholdFibonnacening) { reject "need to collect penalties before calling"; }
if(fibonaccenningProposal[proposalID][0] == false { reject "proposal has been rejected"; }
if(block.timestamp < fibonaccenningProposal[proposalID][1] + delayBeforeEnforce) { reject "delay must expire before proposal valid"; }
if( eventFibonacceningActive = true ) { reject "already active" }
{outsidecontractCall-Masterchef} setRewardPerBlockInMasterchef(currentInflation * fibonaccenningProposal[proposalID][3]);
//WAITWAIT: HOW TO PREVENT MULTIPLE CALLS FOR LEVER PULLZ? IDK
//what happens if there are multiple pulls?
fibonacenningActiveID = proposalID;
fibonacenningActivatedTimestamp = block.timestamp;
eventFibonacceningActive = true;
transfer(thresholdFibonnacening, deadAddress); //send the coins from .this wallet to deadaddress(burn them to perform fibonaccening)
}
//ends inflation boost, reduces inflation
//anyone can call
function endFibonaccening() {
if(eventFibonacceningActive == false) { reject "fibonaccenning not activated" }
if(block.timestamp < fibonacenningActivatedTimestamp + fibonaccenningProposal[fibonacenningActiveID][5]) { reject "not yet expired"
int newamount = calculateFibonaccenningNewRewardPerBlock();
//set new inflation with fibonacci reduction
{outsidecontractCall-Masterchef} setRewardPerBlockInMasterchef(newamount);
eventFibonacceningActive = false;
//does solidity go line by line when executing? Will first line get executed first? If not, then this could be a problem
//update current inflation in global setting to that amount
rewardPerBlockPriorFibonaccening = newamount;
}
struct proposeGrandFibonacenning{
bool valid;
int eventDate;
int proposalTimestamp;
int amountSacrificedForVote;
}
proposeGrandFibonacenning[] public grandFibonacceningProposals;
function initiateProposeGrandFibonacenning(int depositingTokens, int delayFromNow) {
if(depositingTokens > maximumVoteTokens) { "preventing tyranny, maximum 0.05% of tokens" }
if(depositingTokens < costToVote) {"there is a minimum cost to vote"}
if(eligibleGrandFibonacenning ) // WHEN ARE WE ELIGIBLE FOR THIS EVENT?? hmh need to set still
if(delayFromNow < 3days) { reject }
transfer(depositingTokens, deadAddress); //burn senders tokens as "transaction cost"
grandFibonacceningProposals.push("true", block.timestamp + delayFromNow, block.timestamp, depositingTokens); //submit new proposal
}
function vetoProposeGrandFibonacenning(int proposalID, int depositingTokens) {
if (grandFibonacceningProposals[proposalID][0] == "false") { reject "already invalid" }
if(depositingTokens != grandFibonacceningProposals[proposalID][3]) { reject "must match amount to veto"; }
grandFibonacceningProposals[proposalID][0] = "false"; //negate the proposal
transfer(depositingTokens, deadAddress); //burn it as "transaction cost to vote"
}
//the grand fibonnacenning where massive supply is printed in a period of X days
//the duration should be preset to last for 10days roughly
//27 events: 1 hour of boosted rewards where supply goes x1.618 every 12hours or so
bool grandFibonacenningActivated = false;
function theGrandFibonacenningEnforce(proposalID) {
//prepare blockcounters in advance, it will be important
if(expiredGrandFibonaccening) { "already called gtfo"; }
if(!grandFibonacceningProposals[proposalID][0] || grandFibonacceningProposals[proposalID][1] + grandFibonacceningProposals[proposalID][2] < block.timestamp) //not valid
//need to add another function if it has already happened and has been called too
//after event expires set the inflation reduction to become another function!!
grandFibonacenningActivated = true;
//if you multiply by golden ratio whole supply roughly 27times you will get a 1,000,000X coins
//it will look better(higher upside potential), there will be no ceiling(resistances)
//you will be earning more tokens, they will be cheaper,...
//inflation will be lower
int newInflationRate = getTotalSupply() * goldenRatio;
rewardPerBlockPriorFibonaccening = newInflationRate;
/*
MISSING HERE, and grandfibonacenningRunning function.. (need to set somehow for the function to work basically)
*/
}
//function that is executing rewards for grand fibonacenning
int eventCounter = 0;
int lastEventTimestamp;
function grandFibonacenningRunning() {
if(!grandFibonacenningActivated) { reject }
if(getTotalSupply() > 1quadrillion) { grandFibonacenningRunning = false } // expire it somehow and make sure it can't be called no more
//print around 9:00UTC and then do it again around 17:00 UTC every day
//aka make function callable at that time
//also need ot make sure it can't be called again if running
//should we include the tokens in this contract(penalties) or no?
int amountToPrint = getTotalSupply() * 0.6183; // we multiply supply x1.6183(golden raito)
int newRewardPerBlock = amountToPrint / (3600/blocksPerSecond);
{outsidecontractCall-Masterchef} setRewardPerBlockInMasterchef(newRewardPerBlock);
eventCounter++;
}
function gracePeriodTransferOwner() priv admin only {
//reject call after October 15
if(block.timestamp > xxx) { reject "Contract is immutable. Grace period only available in the first month for potentital improvements") }
if(gracePeriodActivation == true) { reject "already activated" }
gracePeriodActivation = true;
timestampGracePeriod = block.timestamp;
}
//works as a time-lock. Transfer owner is called and can only be fulfilled after
function afterDelayOwnership(addres newOwnerAddress) priv admin only{
if(gracePeriodActivation == false) { reject "grace period not request"; }
if(timestampGracePeriod + 9999 < block.timestamp) { rejecc "minimum 10k blocks before initiation"; } // effectively roughly 6hour timelock i think
//checks passed, safe to change ownerships
{outsidecontractCall-Masterchef} transferOwnership(newOwnerAddress); //call masterchef function to transfer ownership
}
//do we need this. i mean does it really matter if there is no function for owner? IDK
//CAN BE CALLED BY ANYBODY, basically make it immutable/controlled by nobody
function renounceOwnership() public anybody(idksyntax) {
if(block.timestamp < 15october) { "grace period expires after 30september" }
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
| negate the proposal
| proposeDurationCalculation[proposalID][0] = "false"; | 1,047,238 | [
1,
82,
4784,
326,
14708,
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
]
| [
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,
0
]
| [
1,
202,
685,
4150,
5326,
13989,
63,
685,
8016,
734,
6362,
20,
65,
273,
315,
5743,
14432,
282,
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
]
|
./full_match/137/0xbA2AA1af8003764F1F3b48BB62d2c61819b5a370/sources/testpolygon.sol | * @title ERC721A Non-Fungible Token Standard, including the Metadata extension. Optimized for lower gas during batch mints. Token IDs are minted in sequential order (e.g. 0, 1, 2, 3, ...) starting from `_startTokenId()`. Assumptions: - An owner cannot have more than 264 - 1 (max value of uint64) of supply. - The maximum token ID cannot exceed 2256 - 1 (max value of uint256)./ Bypass for a `--via-ir` bug (https:github.com/chiru-labs/ERC721A/pull/364). | contract ERC721A is IERC721A {
function totalSupply() external view returns (uint256);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
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) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external payable;
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external payable;
function transferFrom(
address from,
address to,
uint256 tokenId
) external payable;
function approve(address to, uint256 tokenId) external payable;
function setApprovalForAll(address operator, bool _approved) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function isApprovedForAll(address owner, address operator) external view returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
event ConsecutiveTransfer(uint256 indexed fromTokenId, uint256 toTokenId, address indexed from, address indexed to);
}
pragma solidity ^0.8.4;
}
struct TokenApprovalRef {
address value;
}
0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef;
uint256 private constant _BITMASK_ADDRESS_DATA_ENTRY = (1 << 64) - 1;
uint256 private constant _BITPOS_NUMBER_MINTED = 64;
uint256 private constant _BITPOS_NUMBER_BURNED = 128;
uint256 private constant _BITPOS_AUX = 192;
uint256 private constant _BITMASK_AUX_COMPLEMENT = (1 << 192) - 1;
uint256 private constant _BITPOS_START_TIMESTAMP = 160;
uint256 private constant _BITMASK_BURNED = 1 << 224;
uint256 private constant _BITPOS_NEXT_INITIALIZED = 225;
uint256 private constant _BITMASK_NEXT_INITIALIZED = 1 << 225;
uint256 private constant _BITPOS_EXTRA_DATA = 232;
uint256 private constant _BITMASK_EXTRA_DATA_COMPLEMENT = (1 << 232) - 1;
uint256 private constant _BITMASK_ADDRESS = (1 << 160) - 1;
uint256 private constant _MAX_MINT_ERC2309_QUANTITY_LIMIT = 5000;
bytes32 private constant _TRANSFER_EVENT_SIGNATURE =
uint256 private _currentIndex;
uint256 private _burnCounter;
string private _name;
string private _symbol;
mapping(uint256 => uint256) private _packedOwnerships;
mapping(address => uint256) private _packedAddressData;
mapping(uint256 => TokenApprovalRef) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_currentIndex = _startTokenId();
}
function _startTokenId() internal view virtual returns (uint256) {
return 0;
}
function _nextTokenId() internal view virtual returns (uint256) {
return _currentIndex;
}
function totalSupply() public view virtual override returns (uint256) {
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
function totalSupply() public view virtual override returns (uint256) {
unchecked {
return _currentIndex - _burnCounter - _startTokenId();
}
}
function _totalMinted() internal view virtual returns (uint256) {
unchecked {
return _currentIndex - _startTokenId();
}
}
function _totalMinted() internal view virtual returns (uint256) {
unchecked {
return _currentIndex - _startTokenId();
}
}
function _totalBurned() internal view virtual returns (uint256) {
return _burnCounter;
}
function balanceOf(address owner) public view virtual override returns (uint256) {
if (owner == address(0)) _revert(BalanceQueryForZeroAddress.selector);
return _packedAddressData[owner] & _BITMASK_ADDRESS_DATA_ENTRY;
}
function _numberMinted(address owner) internal view returns (uint256) {
return (_packedAddressData[owner] >> _BITPOS_NUMBER_MINTED) & _BITMASK_ADDRESS_DATA_ENTRY;
}
function _numberBurned(address owner) internal view returns (uint256) {
return (_packedAddressData[owner] >> _BITPOS_NUMBER_BURNED) & _BITMASK_ADDRESS_DATA_ENTRY;
}
function _getAux(address owner) internal view returns (uint64) {
return uint64(_packedAddressData[owner] >> _BITPOS_AUX);
}
function _setAux(address owner, uint64 aux) internal virtual {
uint256 packed = _packedAddressData[owner];
uint256 auxCasted;
assembly {
auxCasted := aux
}
packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
_packedAddressData[owner] = packed;
}
function _setAux(address owner, uint64 aux) internal virtual {
uint256 packed = _packedAddressData[owner];
uint256 auxCasted;
assembly {
auxCasted := aux
}
packed = (packed & _BITMASK_AUX_COMPLEMENT) | (auxCasted << _BITPOS_AUX);
_packedAddressData[owner] = packed;
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) _revert(URIQueryForNonexistentToken.selector);
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, _toString(tokenId))) : '';
}
function _baseURI() internal view virtual returns (string memory) {
return '';
}
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
return address(uint160(_packedOwnershipOf(tokenId)));
}
function _ownershipOf(uint256 tokenId) internal view virtual returns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnershipOf(tokenId));
}
function _ownershipAt(uint256 index) internal view virtual returns (TokenOwnership memory) {
return _unpackedOwnership(_packedOwnerships[index]);
}
function _ownershipIsInitialized(uint256 index) internal view virtual returns (bool) {
return _packedOwnerships[index] != 0;
}
function _initializeOwnershipAt(uint256 index) internal virtual {
if (_packedOwnerships[index] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
function _initializeOwnershipAt(uint256 index) internal virtual {
if (_packedOwnerships[index] == 0) {
_packedOwnerships[index] = _packedOwnershipOf(index);
}
}
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
if (_startTokenId() <= tokenId) {
packed = _packedOwnerships[tokenId];
if (packed == 0) {
if (tokenId >= _currentIndex) _revert(OwnerQueryForNonexistentToken.selector);
for (;;) {
unchecked {
packed = _packedOwnerships[--tokenId];
}
if (packed == 0) continue;
if (packed & _BITMASK_BURNED == 0) return packed;
}
}
}
_revert(OwnerQueryForNonexistentToken.selector);
}
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
if (_startTokenId() <= tokenId) {
packed = _packedOwnerships[tokenId];
if (packed == 0) {
if (tokenId >= _currentIndex) _revert(OwnerQueryForNonexistentToken.selector);
for (;;) {
unchecked {
packed = _packedOwnerships[--tokenId];
}
if (packed == 0) continue;
if (packed & _BITMASK_BURNED == 0) return packed;
}
}
}
_revert(OwnerQueryForNonexistentToken.selector);
}
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
if (_startTokenId() <= tokenId) {
packed = _packedOwnerships[tokenId];
if (packed == 0) {
if (tokenId >= _currentIndex) _revert(OwnerQueryForNonexistentToken.selector);
for (;;) {
unchecked {
packed = _packedOwnerships[--tokenId];
}
if (packed == 0) continue;
if (packed & _BITMASK_BURNED == 0) return packed;
}
}
}
_revert(OwnerQueryForNonexistentToken.selector);
}
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
if (_startTokenId() <= tokenId) {
packed = _packedOwnerships[tokenId];
if (packed == 0) {
if (tokenId >= _currentIndex) _revert(OwnerQueryForNonexistentToken.selector);
for (;;) {
unchecked {
packed = _packedOwnerships[--tokenId];
}
if (packed == 0) continue;
if (packed & _BITMASK_BURNED == 0) return packed;
}
}
}
_revert(OwnerQueryForNonexistentToken.selector);
}
function _packedOwnershipOf(uint256 tokenId) private view returns (uint256 packed) {
if (_startTokenId() <= tokenId) {
packed = _packedOwnerships[tokenId];
if (packed == 0) {
if (tokenId >= _currentIndex) _revert(OwnerQueryForNonexistentToken.selector);
for (;;) {
unchecked {
packed = _packedOwnerships[--tokenId];
}
if (packed == 0) continue;
if (packed & _BITMASK_BURNED == 0) return packed;
}
}
}
_revert(OwnerQueryForNonexistentToken.selector);
}
_revert(OwnerQueryForNonexistentToken.selector);
if (packed & _BITMASK_BURNED == 0) return packed;
function _unpackedOwnership(uint256 packed) private pure returns (TokenOwnership memory ownership) {
ownership.addr = address(uint160(packed));
ownership.startTimestamp = uint64(packed >> _BITPOS_START_TIMESTAMP);
ownership.burned = packed & _BITMASK_BURNED != 0;
ownership.extraData = uint24(packed >> _BITPOS_EXTRA_DATA);
}
function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
assembly {
owner := and(owner, _BITMASK_ADDRESS)
result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
}
}
function _packOwnershipData(address owner, uint256 flags) private view returns (uint256 result) {
assembly {
owner := and(owner, _BITMASK_ADDRESS)
result := or(owner, or(shl(_BITPOS_START_TIMESTAMP, timestamp()), flags))
}
}
function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
assembly {
result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
function _nextInitializedFlag(uint256 quantity) private pure returns (uint256 result) {
assembly {
result := shl(_BITPOS_NEXT_INITIALIZED, eq(quantity, 1))
}
}
function approve(address to, uint256 tokenId) public payable virtual override {
_approve(to, tokenId, true);
}
function getApproved(uint256 tokenId) public view virtual override returns (address) {
if (!_exists(tokenId)) _revert(ApprovalQueryForNonexistentToken.selector);
return _tokenApprovals[tokenId].value;
}
function setApprovalForAll(address operator, bool approved) public virtual override {
_operatorApprovals[_msgSenderERC721A()][operator] = approved;
emit ApprovalForAll(_msgSenderERC721A(), operator, approved);
}
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
function _exists(uint256 tokenId) internal view virtual returns (bool result) {
if (_startTokenId() <= tokenId) {
if (tokenId < _currentIndex) {
uint256 packed;
while ((packed = _packedOwnerships[tokenId]) == 0) --tokenId;
result = packed & _BITMASK_BURNED == 0;
}
}
}
function _exists(uint256 tokenId) internal view virtual returns (bool result) {
if (_startTokenId() <= tokenId) {
if (tokenId < _currentIndex) {
uint256 packed;
while ((packed = _packedOwnerships[tokenId]) == 0) --tokenId;
result = packed & _BITMASK_BURNED == 0;
}
}
}
function _exists(uint256 tokenId) internal view virtual returns (bool result) {
if (_startTokenId() <= tokenId) {
if (tokenId < _currentIndex) {
uint256 packed;
while ((packed = _packedOwnerships[tokenId]) == 0) --tokenId;
result = packed & _BITMASK_BURNED == 0;
}
}
}
function _isSenderApprovedOrOwner(
address approvedAddress,
address owner,
address msgSender
) private pure returns (bool result) {
assembly {
owner := and(owner, _BITMASK_ADDRESS)
msgSender := and(msgSender, _BITMASK_ADDRESS)
result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
}
}
function _isSenderApprovedOrOwner(
address approvedAddress,
address owner,
address msgSender
) private pure returns (bool result) {
assembly {
owner := and(owner, _BITMASK_ADDRESS)
msgSender := and(msgSender, _BITMASK_ADDRESS)
result := or(eq(msgSender, owner), eq(msgSender, approvedAddress))
}
}
function _getApprovedSlotAndAddress(uint256 tokenId)
private
view
returns (uint256 approvedAddressSlot, address approvedAddress)
{
TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
assembly {
approvedAddressSlot := tokenApproval.slot
approvedAddress := sload(approvedAddressSlot)
}
}
function _getApprovedSlotAndAddress(uint256 tokenId)
private
view
returns (uint256 approvedAddressSlot, address approvedAddress)
{
TokenApprovalRef storage tokenApproval = _tokenApprovals[tokenId];
assembly {
approvedAddressSlot := tokenApproval.slot
approvedAddress := sload(approvedAddressSlot)
}
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));
if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
assembly {
log4(
)
}
if (toMasked == 0) _revert(TransferToZeroAddress.selector);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));
if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
assembly {
log4(
)
}
if (toMasked == 0) _revert(TransferToZeroAddress.selector);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));
if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
assembly {
log4(
)
}
if (toMasked == 0) _revert(TransferToZeroAddress.selector);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));
if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
assembly {
log4(
)
}
if (toMasked == 0) _revert(TransferToZeroAddress.selector);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));
if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
assembly {
log4(
)
}
if (toMasked == 0) _revert(TransferToZeroAddress.selector);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));
if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
assembly {
log4(
)
}
if (toMasked == 0) _revert(TransferToZeroAddress.selector);
_afterTokenTransfers(from, to, tokenId, 1);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));
if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
assembly {
log4(
)
}
if (toMasked == 0) _revert(TransferToZeroAddress.selector);
_afterTokenTransfers(from, to, tokenId, 1);
}
uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
from = address(uint160(uint256(uint160(from)) & _BITMASK_ADDRESS));
if (address(uint160(prevOwnershipPacked)) != from) _revert(TransferFromIncorrectOwner.selector);
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
_beforeTokenTransfers(from, to, tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedOwnerships[tokenId] = _packOwnershipData(
to,
_BITMASK_NEXT_INITIALIZED | _nextExtraData(from, to, prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
assembly {
log4(
)
}
if (toMasked == 0) _revert(TransferToZeroAddress.selector);
_afterTokenTransfers(from, to, tokenId, 1);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable virtual override {
safeTransferFrom(from, to, tokenId, '');
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public payable virtual override {
transferFrom(from, to, tokenId);
if (to.code.length != 0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public payable virtual override {
transferFrom(from, to, tokenId);
if (to.code.length != 0)
if (!_checkContractOnERC721Received(from, to, tokenId, _data)) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
}
) internal virtual {}
) internal virtual {}
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
assembly {
revert(add(32, reason), mload(reason))
}
}
}
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} catch (bytes memory reason) {
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
assembly {
revert(add(32, reason), mload(reason))
}
}
}
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _checkContractOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
try ERC721A__IERC721Receiver(to).onERC721Received(_msgSenderERC721A(), from, tokenId, _data) returns (
bytes4 retval
) {
return retval == ERC721A__IERC721Receiver(to).onERC721Received.selector;
if (reason.length == 0) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
assembly {
revert(add(32, reason), mload(reason))
}
}
}
function _mint(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (quantity == 0) _revert(MintZeroQuantity.selector);
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
_packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
if (toMasked == 0) _revert(MintToZeroAddress.selector);
uint256 end = startTokenId + quantity;
uint256 tokenId = startTokenId;
do {
assembly {
log4(
)
}
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mint(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (quantity == 0) _revert(MintZeroQuantity.selector);
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
_packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
if (toMasked == 0) _revert(MintToZeroAddress.selector);
uint256 end = startTokenId + quantity;
uint256 tokenId = startTokenId;
do {
assembly {
log4(
)
}
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mint(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (quantity == 0) _revert(MintZeroQuantity.selector);
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
_packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
if (toMasked == 0) _revert(MintToZeroAddress.selector);
uint256 end = startTokenId + quantity;
uint256 tokenId = startTokenId;
do {
assembly {
log4(
)
}
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mint(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (quantity == 0) _revert(MintZeroQuantity.selector);
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
_packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
uint256 toMasked = uint256(uint160(to)) & _BITMASK_ADDRESS;
if (toMasked == 0) _revert(MintToZeroAddress.selector);
uint256 end = startTokenId + quantity;
uint256 tokenId = startTokenId;
do {
assembly {
log4(
)
}
_currentIndex = end;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
} while (++tokenId != end);
function _mintERC2309(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (to == address(0)) _revert(MintToZeroAddress.selector);
if (quantity == 0) _revert(MintZeroQuantity.selector);
if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) _revert(MintERC2309QuantityExceedsLimit.selector);
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
_currentIndex = startTokenId + quantity;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _mintERC2309(address to, uint256 quantity) internal virtual {
uint256 startTokenId = _currentIndex;
if (to == address(0)) _revert(MintToZeroAddress.selector);
if (quantity == 0) _revert(MintZeroQuantity.selector);
if (quantity > _MAX_MINT_ERC2309_QUANTITY_LIMIT) _revert(MintERC2309QuantityExceedsLimit.selector);
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
unchecked {
_packedAddressData[to] += quantity * ((1 << _BITPOS_NUMBER_MINTED) | 1);
_packedOwnerships[startTokenId] = _packOwnershipData(
to,
_nextInitializedFlag(quantity) | _nextExtraData(address(0), to, 0)
);
emit ConsecutiveTransfer(startTokenId, startTokenId + quantity - 1, address(0), to);
_currentIndex = startTokenId + quantity;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
} while (index < end);
}
}
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
} while (index < end);
}
}
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
} while (index < end);
}
}
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
} while (index < end);
}
}
}
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal virtual {
_mint(to, quantity);
unchecked {
if (to.code.length != 0) {
uint256 end = _currentIndex;
uint256 index = end - quantity;
do {
if (!_checkContractOnERC721Received(address(0), to, index++, _data)) {
_revert(TransferToNonERC721ReceiverImplementer.selector);
}
} while (index < end);
}
}
}
if (_currentIndex != end) _revert(bytes4(0));
function _safeMint(address to, uint256 quantity) internal virtual {
_safeMint(to, quantity, '');
}
function _approve(address to, uint256 tokenId) internal virtual {
_approve(to, tokenId, false);
}
function _approve(
address to,
uint256 tokenId,
bool approvalCheck
) internal virtual {
address owner = ownerOf(tokenId);
if (approvalCheck && _msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
_revert(ApprovalCallerNotOwnerNorApproved.selector);
}
_tokenApprovals[tokenId].value = to;
emit Approval(owner, to, tokenId);
}
function _approve(
address to,
uint256 tokenId,
bool approvalCheck
) internal virtual {
address owner = ownerOf(tokenId);
if (approvalCheck && _msgSenderERC721A() != owner)
if (!isApprovedForAll(owner, _msgSenderERC721A())) {
_revert(ApprovalCallerNotOwnerNorApproved.selector);
}
_tokenApprovals[tokenId].value = to;
emit Approval(owner, to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, false);
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _burn(uint256 tokenId, bool approvalCheck) internal virtual {
uint256 prevOwnershipPacked = _packedOwnershipOf(tokenId);
address from = address(uint160(prevOwnershipPacked));
(uint256 approvedAddressSlot, address approvedAddress) = _getApprovedSlotAndAddress(tokenId);
if (approvalCheck) {
if (!_isSenderApprovedOrOwner(approvedAddress, from, _msgSenderERC721A()))
if (!isApprovedForAll(from, _msgSenderERC721A())) _revert(TransferCallerNotOwnerNorApproved.selector);
}
_beforeTokenTransfers(from, address(0), tokenId, 1);
assembly {
if approvedAddress {
sstore(approvedAddressSlot, 0)
}
}
unchecked {
_packedAddressData[from] += (1 << _BITPOS_NUMBER_BURNED) - 1;
_packedOwnerships[tokenId] = _packOwnershipData(
from,
(_BITMASK_BURNED | _BITMASK_NEXT_INITIALIZED) | _nextExtraData(from, address(0), prevOwnershipPacked)
);
if (prevOwnershipPacked & _BITMASK_NEXT_INITIALIZED == 0) {
uint256 nextTokenId = tokenId + 1;
if (_packedOwnerships[nextTokenId] == 0) {
if (nextTokenId != _currentIndex) {
_packedOwnerships[nextTokenId] = prevOwnershipPacked;
}
}
}
}
emit Transfer(from, address(0), tokenId);
_afterTokenTransfers(from, address(0), tokenId, 1);
unchecked {
_burnCounter++;
}
}
function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
uint256 packed = _packedOwnerships[index];
if (packed == 0) _revert(OwnershipNotInitializedForExtraData.selector);
uint256 extraDataCasted;
assembly {
extraDataCasted := extraData
}
packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
function _setExtraDataAt(uint256 index, uint24 extraData) internal virtual {
uint256 packed = _packedOwnerships[index];
if (packed == 0) _revert(OwnershipNotInitializedForExtraData.selector);
uint256 extraDataCasted;
assembly {
extraDataCasted := extraData
}
packed = (packed & _BITMASK_EXTRA_DATA_COMPLEMENT) | (extraDataCasted << _BITPOS_EXTRA_DATA);
_packedOwnerships[index] = packed;
}
) internal view virtual returns (uint24) {}
function _extraData(
address from,
address to,
uint24 previousExtraData
function _nextExtraData(
address from,
address to,
uint256 prevOwnershipPacked
) private view returns (uint256) {
uint24 extraData = uint24(prevOwnershipPacked >> _BITPOS_EXTRA_DATA);
return uint256(_extraData(from, to, extraData)) << _BITPOS_EXTRA_DATA;
}
function _msgSenderERC721A() internal view virtual returns (address) {
return msg.sender;
}
function _toString(uint256 value) internal pure virtual returns (string memory str) {
assembly {
let m := add(mload(0x40), 0xa0)
mstore(0x40, m)
str := sub(m, 0x20)
mstore(str, 0)
let end := str
str := sub(str, 1)
mstore8(str, add(48, mod(temp, 10)))
temp := div(temp, 10)
}
let length := sub(end, str)
}
function _toString(uint256 value) internal pure virtual returns (string memory str) {
assembly {
let m := add(mload(0x40), 0xa0)
mstore(0x40, m)
str := sub(m, 0x20)
mstore(str, 0)
let end := str
str := sub(str, 1)
mstore8(str, add(48, mod(temp, 10)))
temp := div(temp, 10)
}
let length := sub(end, str)
}
for { let temp := value } 1 {} {
if iszero(temp) { break }
str := sub(str, 0x20)
mstore(str, length)
}
| 3,739,680 | [
1,
654,
39,
27,
5340,
37,
3858,
17,
42,
20651,
1523,
3155,
8263,
16,
6508,
326,
6912,
2710,
18,
19615,
1235,
364,
2612,
16189,
4982,
2581,
312,
28142,
18,
3155,
7115,
854,
312,
474,
329,
316,
21210,
1353,
261,
73,
18,
75,
18,
374,
16,
404,
16,
576,
16,
890,
16,
1372,
13,
5023,
628,
1375,
67,
1937,
1345,
548,
1435,
8338,
4725,
379,
573,
30,
300,
1922,
3410,
2780,
1240,
1898,
2353,
576,
1105,
300,
404,
261,
1896,
460,
434,
2254,
1105,
13,
434,
14467,
18,
300,
1021,
4207,
1147,
1599,
2780,
9943,
576,
5034,
300,
404,
261,
1896,
460,
434,
2254,
5034,
2934,
19,
605,
25567,
364,
279,
1375,
413,
21985,
17,
481,
68,
7934,
261,
4528,
30,
6662,
18,
832,
19,
343,
481,
89,
17,
80,
5113,
19,
654,
39,
27,
5340,
37,
19,
13469,
19,
23,
1105,
2934,
2,
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,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4232,
39,
27,
5340,
37,
353,
467,
654,
39,
27,
5340,
37,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
203,
565,
871,
12279,
12,
2867,
8808,
628,
16,
1758,
8808,
358,
16,
2254,
5034,
8808,
1147,
548,
1769,
203,
203,
565,
871,
1716,
685,
1125,
12,
2867,
8808,
3410,
16,
1758,
8808,
20412,
16,
2254,
5034,
8808,
1147,
548,
1769,
203,
203,
565,
871,
1716,
685,
1125,
1290,
1595,
12,
2867,
8808,
3410,
16,
1758,
8808,
3726,
16,
1426,
20412,
1769,
203,
203,
565,
445,
11013,
951,
12,
2867,
3410,
13,
3903,
1476,
1135,
261,
11890,
5034,
11013,
1769,
203,
203,
565,
445,
3410,
951,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
2867,
3410,
1769,
203,
203,
565,
445,
4183,
5912,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1731,
745,
892,
501,
203,
565,
262,
3903,
8843,
429,
31,
203,
203,
565,
445,
4183,
5912,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
3903,
8843,
429,
31,
203,
203,
565,
445,
7412,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
203,
565,
262,
3903,
8843,
429,
31,
203,
203,
565,
445,
6617,
537,
12,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.7.0;
pragma experimental ABIEncoderV2;
// File: witnet-ethereum-block-relay/contracts/BlockRelayInterface.sol
/**
* @title Block Relay Interface
* @notice Interface of a Block Relay to a Witnet network
* It defines how to interact with the Block Relay in order to support:
* - Retrieve last beacon information
* - Verify proof of inclusions (PoIs) of data request and tally transactions
* @author Witnet Foundation
*/
interface BlockRelayInterface {
/// @notice Returns the beacon from the last inserted block.
/// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility.
/// @return last beacon in bytes
function getLastBeacon() external view returns(bytes memory);
/// @notice Returns the lastest epoch reported to the block relay.
/// @return epoch
function getLastEpoch() external view returns(uint256);
/// @notice Returns the latest hash reported to the block relay
/// @return blockhash
function getLastHash() external view returns(uint256);
/// @notice Verifies the validity of a data request PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element) external view returns(bool);
/// @notice Verifies the validity of a tally PoI against the Tally merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid tally PoI
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element) external view returns(bool);
/// @notice Verifies if the block relay can be upgraded
/// @return true if contract is upgradable
function isUpgradable(address _address) external view returns(bool);
}
// File: witnet-ethereum-block-relay/contracts/CentralizedBlockRelay.sol
/**
* @title Block relay contract
* @notice Contract to store/read block headers from the Witnet network
* @author Witnet Foundation
*/
contract CentralizedBlockRelay is BlockRelayInterface {
struct MerkleRoots {
// hash of the merkle root of the DRs in Witnet
uint256 drHashMerkleRoot;
// hash of the merkle root of the tallies in Witnet
uint256 tallyHashMerkleRoot;
}
struct Beacon {
// hash of the last block
uint256 blockHash;
// epoch of the last block
uint256 epoch;
}
// Address of the block pusher
address public witnet;
// Last block reported
Beacon public lastBlock;
mapping (uint256 => MerkleRoots) public blocks;
// Event emitted when a new block is posted to the contract
event NewBlock(address indexed _from, uint256 _id);
// Only the owner should be able to push blocks
modifier isOwner() {
require(msg.sender == witnet, "Sender not authorized"); // If it is incorrect here, it reverts.
_; // Otherwise, it continues.
}
// Ensures block exists
modifier blockExists(uint256 _id){
require(blocks[_id].drHashMerkleRoot!=0, "Non-existing block");
_;
}
// Ensures block does not exist
modifier blockDoesNotExist(uint256 _id){
require(blocks[_id].drHashMerkleRoot==0, "The block already existed");
_;
}
constructor() public{
// Only the contract deployer is able to push blocks
witnet = msg.sender;
}
/// @dev Read the beacon of the last block inserted
/// @return bytes to be signed by bridge nodes
function getLastBeacon()
external
view
override
returns(bytes memory)
{
return abi.encodePacked(lastBlock.blockHash, lastBlock.epoch);
}
/// @notice Returns the lastest epoch reported to the block relay.
/// @return epoch
function getLastEpoch() external view override returns(uint256) {
return lastBlock.epoch;
}
/// @notice Returns the latest hash reported to the block relay
/// @return blockhash
function getLastHash() external view override returns(uint256) {
return lastBlock.blockHash;
}
/// @dev Verifies the validity of a PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true or false depending the validity
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element)
external
view
override
blockExists(_blockHash)
returns(bool)
{
uint256 drMerkleRoot = blocks[_blockHash].drHashMerkleRoot;
return(verifyPoi(
_poi,
drMerkleRoot,
_index,
_element));
}
/// @dev Verifies the validity of a PoI against the tally merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the element
/// @return true or false depending the validity
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _index,
uint256 _element)
external
view
override
blockExists(_blockHash)
returns(bool)
{
uint256 tallyMerkleRoot = blocks[_blockHash].tallyHashMerkleRoot;
return(verifyPoi(
_poi,
tallyMerkleRoot,
_index,
_element));
}
/// @dev Verifies if the contract is upgradable
/// @return true if the contract upgradable
function isUpgradable(address _address) external view override returns(bool) {
if (_address == witnet) {
return true;
}
return false;
}
/// @dev Post new block into the block relay
/// @param _blockHash Hash of the block header
/// @param _epoch Witnet epoch to which the block belongs to
/// @param _drMerkleRoot Merkle root belonging to the data requests
/// @param _tallyMerkleRoot Merkle root belonging to the tallies
function postNewBlock(
uint256 _blockHash,
uint256 _epoch,
uint256 _drMerkleRoot,
uint256 _tallyMerkleRoot)
external
isOwner
blockDoesNotExist(_blockHash)
{
lastBlock.blockHash = _blockHash;
lastBlock.epoch = _epoch;
blocks[_blockHash].drHashMerkleRoot = _drMerkleRoot;
blocks[_blockHash].tallyHashMerkleRoot = _tallyMerkleRoot;
emit NewBlock(witnet, _blockHash);
}
/// @dev Retrieve the requests-only merkle root hash that was reported for a specific block header.
/// @param _blockHash Hash of the block header
/// @return Requests-only merkle root hash in the block header.
function readDrMerkleRoot(uint256 _blockHash)
external
view
blockExists(_blockHash)
returns(uint256)
{
return blocks[_blockHash].drHashMerkleRoot;
}
/// @dev Retrieve the tallies-only merkle root hash that was reported for a specific block header.
/// @param _blockHash Hash of the block header.
/// @return tallies-only merkle root hash in the block header.
function readTallyMerkleRoot(uint256 _blockHash)
external
view
blockExists(_blockHash)
returns(uint256)
{
return blocks[_blockHash].tallyHashMerkleRoot;
}
/// @dev Verifies the validity of a PoI
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _root the merkle root
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true or false depending the validity
function verifyPoi(
uint256[] memory _poi,
uint256 _root,
uint256 _index,
uint256 _element)
private pure returns(bool)
{
uint256 tree = _element;
uint256 index = _index;
// We want to prove that the hash of the _poi and the _element is equal to _root
// For knowing if concatenate to the left or the right we check the parity of the the index
for (uint i = 0; i < _poi.length; i++) {
if (index%2 == 0) {
tree = uint256(sha256(abi.encodePacked(tree, _poi[i])));
} else {
tree = uint256(sha256(abi.encodePacked(_poi[i], tree)));
}
index = index >> 1;
}
return _root == tree;
}
}
// File: witnet-ethereum-block-relay/contracts/BlockRelayProxy.sol
/**
* @title Block Relay Proxy
* @notice Contract to act as a proxy between the Witnet Bridge Interface and the block relay
* @dev More information can be found here
* DISCLAIMER: this is a work in progress, meaning the contract could be voulnerable to attacks
* @author Witnet Foundation
*/
contract BlockRelayProxy {
// Address of the current controller
address internal blockRelayAddress;
// Current interface to the controller
BlockRelayInterface internal blockRelayInstance;
struct ControllerInfo {
// last epoch seen by a controller
uint256 lastEpoch;
// address of the controller
address blockRelayController;
}
// array containing the information about controllers
ControllerInfo[] internal controllers;
modifier notIdentical(address _newAddress) {
require(_newAddress != blockRelayAddress, "The provided Block Relay instance address is already in use");
_;
}
constructor(address _blockRelayAddress) public {
// Initialize the first epoch pointing to the first controller
controllers.push(ControllerInfo({lastEpoch: 0, blockRelayController: _blockRelayAddress}));
blockRelayAddress = _blockRelayAddress;
blockRelayInstance = BlockRelayInterface(_blockRelayAddress);
}
/// @notice Returns the beacon from the last inserted block.
/// The last beacon (in bytes) will be used by Witnet Bridge nodes to compute their eligibility.
/// @return last beacon in bytes
function getLastBeacon() external view returns(bytes memory) {
return blockRelayInstance.getLastBeacon();
}
/// @notice Returns the last Wtinet epoch known to the block relay instance.
/// @return The last epoch is used in the WRB to avoid reusage of PoI in a data request.
function getLastEpoch() external view returns(uint256) {
return blockRelayInstance.getLastEpoch();
}
/// @notice Verifies the validity of a data request PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _epoch the epoch of the blockchash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyDrPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _epoch,
uint256 _index,
uint256 _element) external view returns(bool)
{
address controller = getController(_epoch);
return BlockRelayInterface(controller).verifyDrPoi(
_poi,
_blockHash,
_index,
_element);
}
/// @notice Verifies the validity of a tally PoI against the DR merkle root
/// @param _poi the proof of inclusion as [sibling1, sibling2,..]
/// @param _blockHash the blockHash
/// @param _epoch the epoch of the blockchash
/// @param _index the index in the merkle tree of the element to verify
/// @param _element the leaf to be verified
/// @return true if valid data request PoI
function verifyTallyPoi(
uint256[] calldata _poi,
uint256 _blockHash,
uint256 _epoch,
uint256 _index,
uint256 _element) external view returns(bool)
{
address controller = getController(_epoch);
return BlockRelayInterface(controller).verifyTallyPoi(
_poi,
_blockHash,
_index,
_element);
}
/// @notice Upgrades the block relay if the current one is upgradeable
/// @param _newAddress address of the new block relay to upgrade
function upgradeBlockRelay(address _newAddress) external notIdentical(_newAddress) {
// Check if the controller is upgradeable
require(blockRelayInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation");
// Get last epoch seen by the replaced controller
uint256 epoch = blockRelayInstance.getLastEpoch();
// Get the length of last epochs seen by the different controllers
uint256 n = controllers.length;
// If the the last epoch seen by the replaced controller is lower than the one already anotated e.g. 0
// just update the already anotated epoch with the new address, ignoring the previously inserted controller
// Else, anotate the epoch from which the new controller should start receiving blocks
if (epoch < controllers[n-1].lastEpoch) {
controllers[n-1].blockRelayController = _newAddress;
} else {
controllers.push(ControllerInfo({lastEpoch: epoch+1, blockRelayController: _newAddress}));
}
// Update instance
blockRelayAddress = _newAddress;
blockRelayInstance = BlockRelayInterface(_newAddress);
}
/// @notice Gets the controller associated with the BR controller corresponding to the epoch provided
/// @param _epoch the epoch to work with
function getController(uint256 _epoch) public view returns(address _controller) {
// Get length of all last epochs seen by controllers
uint256 n = controllers.length;
// Go backwards until we find the controller having that blockhash
for (uint i = n; i > 0; i--) {
if (_epoch >= controllers[i-1].lastEpoch) {
return (controllers[i-1].blockRelayController);
}
}
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(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: elliptic-curve-solidity/contracts/EllipticCurve.sol
/**
* @title Elliptic Curve Library
* @dev Library providing arithmetic operations over elliptic curves.
* @author Witnet Foundation
*/
library EllipticCurve {
/// @dev Modular euclidean inverse of a number (mod p).
/// @param _x The number
/// @param _pp The modulus
/// @return q such that x*q = 1 (mod _pp)
function invMod(uint256 _x, uint256 _pp) internal pure returns (uint256) {
require(_x != 0 && _x != _pp && _pp != 0, "Invalid number");
uint256 q = 0;
uint256 newT = 1;
uint256 r = _pp;
uint256 newR = _x;
uint256 t;
while (newR != 0) {
t = r / newR;
(q, newT) = (newT, addmod(q, (_pp - mulmod(t, newT, _pp)), _pp));
(r, newR) = (newR, r - t * newR );
}
return q;
}
/// @dev Modular exponentiation, b^e % _pp.
/// Source: https://github.com/androlo/standard-contracts/blob/master/contracts/src/crypto/ECCMath.sol
/// @param _base base
/// @param _exp exponent
/// @param _pp modulus
/// @return r such that r = b**e (mod _pp)
function expMod(uint256 _base, uint256 _exp, uint256 _pp) internal pure returns (uint256) {
require(_pp!=0, "Modulus is zero");
if (_base == 0)
return 0;
if (_exp == 0)
return 1;
uint256 r = 1;
uint256 bit = 2 ** 255;
assembly {
for { } gt(bit, 0) { }{
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, bit)))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 2))))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 4))))), _pp)
r := mulmod(mulmod(r, r, _pp), exp(_base, iszero(iszero(and(_exp, div(bit, 8))))), _pp)
bit := div(bit, 16)
}
}
return r;
}
/// @dev Converts a point (x, y, z) expressed in Jacobian coordinates to affine coordinates (x', y', 1).
/// @param _x coordinate x
/// @param _y coordinate y
/// @param _z coordinate z
/// @param _pp the modulus
/// @return (x', y') affine coordinates
function toAffine(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _pp)
internal pure returns (uint256, uint256)
{
uint256 zInv = invMod(_z, _pp);
uint256 zInv2 = mulmod(zInv, zInv, _pp);
uint256 x2 = mulmod(_x, zInv2, _pp);
uint256 y2 = mulmod(_y, mulmod(zInv, zInv2, _pp), _pp);
return (x2, y2);
}
/// @dev Derives the y coordinate from a compressed-format point x [[SEC-1]](https://www.secg.org/SEC1-Ver-1.0.pdf).
/// @param _prefix parity byte (0x02 even, 0x03 odd)
/// @param _x coordinate x
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return y coordinate y
function deriveY(
uint8 _prefix,
uint256 _x,
uint256 _aa,
uint256 _bb,
uint256 _pp)
internal pure returns (uint256)
{
require(_prefix == 0x02 || _prefix == 0x03, "Invalid compressed EC point prefix");
// x^3 + ax + b
uint256 y2 = addmod(mulmod(_x, mulmod(_x, _x, _pp), _pp), addmod(mulmod(_x, _aa, _pp), _bb, _pp), _pp);
y2 = expMod(y2, (_pp + 1) / 4, _pp);
// uint256 cmp = yBit ^ y_ & 1;
uint256 y = (y2 + _prefix) % 2 == 0 ? y2 : _pp - y2;
return y;
}
/// @dev Check whether point (x,y) is on curve defined by a, b, and _pp.
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of curve
/// @param _bb constant of curve
/// @param _pp the modulus
/// @return true if x,y in the curve, false else
function isOnCurve(
uint _x,
uint _y,
uint _aa,
uint _bb,
uint _pp)
internal pure returns (bool)
{
if (0 == _x || _x == _pp || 0 == _y || _y == _pp) {
return false;
}
// y^2
uint lhs = mulmod(_y, _y, _pp);
// x^3
uint rhs = mulmod(mulmod(_x, _x, _pp), _x, _pp);
if (_aa != 0) {
// x^3 + a*x
rhs = addmod(rhs, mulmod(_x, _aa, _pp), _pp);
}
if (_bb != 0) {
// x^3 + a*x + b
rhs = addmod(rhs, _bb, _pp);
}
return lhs == rhs;
}
/// @dev Calculate inverse (x, -y) of point (x, y).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _pp the modulus
/// @return (x, -y)
function ecInv(
uint256 _x,
uint256 _y,
uint256 _pp)
internal pure returns (uint256, uint256)
{
return (_x, (_pp - _y) % _pp);
}
/// @dev Add two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1+P2 in affine coordinates
function ecAdd(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
uint x = 0;
uint y = 0;
uint z = 0;
// Double if x1==x2 else add
if (_x1==_x2) {
(x, y, z) = jacDouble(
_x1,
_y1,
1,
_aa,
_pp);
} else {
(x, y, z) = jacAdd(
_x1,
_y1,
1,
_x2,
_y2,
1,
_pp);
}
// Get back to affine
return toAffine(
x,
y,
z,
_pp);
}
/// @dev Substract two points (x1, y1) and (x2, y2) in affine coordinates.
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _x2 coordinate x of P2
/// @param _y2 coordinate y of P2
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = P1-P2 in affine coordinates
function ecSub(
uint256 _x1,
uint256 _y1,
uint256 _x2,
uint256 _y2,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
// invert square
(uint256 x, uint256 y) = ecInv(_x2, _y2, _pp);
// P1-square
return ecAdd(
_x1,
_y1,
x,
y,
_aa,
_pp);
}
/// @dev Multiply point (x1, y1, z1) times d in affine coordinates.
/// @param _k scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _aa constant of the curve
/// @param _pp the modulus
/// @return (qx, qy) = d*P in affine coordinates
function ecMul(
uint256 _k,
uint256 _x,
uint256 _y,
uint256 _aa,
uint256 _pp)
internal pure returns(uint256, uint256)
{
// Jacobian multiplication
(uint256 x1, uint256 y1, uint256 z1) = jacMul(
_k,
_x,
_y,
1,
_aa,
_pp);
// Get back to affine
return toAffine(
x1,
y1,
z1,
_pp);
}
/// @dev Adds two points (x1, y1, z1) and (x2 y2, z2).
/// @param _x1 coordinate x of P1
/// @param _y1 coordinate y of P1
/// @param _z1 coordinate z of P1
/// @param _x2 coordinate x of square
/// @param _y2 coordinate y of square
/// @param _z2 coordinate z of square
/// @param _pp the modulus
/// @return (qx, qy, qz) P1+square in Jacobian
function jacAdd(
uint256 _x1,
uint256 _y1,
uint256 _z1,
uint256 _x2,
uint256 _y2,
uint256 _z2,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
if ((_x1==0)&&(_y1==0))
return (_x2, _y2, _z2);
if ((_x2==0)&&(_y2==0))
return (_x1, _y1, _z1);
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
uint[4] memory zs; // z1^2, z1^3, z2^2, z2^3
zs[0] = mulmod(_z1, _z1, _pp);
zs[1] = mulmod(_z1, zs[0], _pp);
zs[2] = mulmod(_z2, _z2, _pp);
zs[3] = mulmod(_z2, zs[2], _pp);
// u1, s1, u2, s2
zs = [
mulmod(_x1, zs[2], _pp),
mulmod(_y1, zs[3], _pp),
mulmod(_x2, zs[0], _pp),
mulmod(_y2, zs[1], _pp)
];
// In case of zs[0] == zs[2] && zs[1] == zs[3], double function should be used
require(zs[0] != zs[2], "Invalid data");
uint[4] memory hr;
//h
hr[0] = addmod(zs[2], _pp - zs[0], _pp);
//r
hr[1] = addmod(zs[3], _pp - zs[1], _pp);
//h^2
hr[2] = mulmod(hr[0], hr[0], _pp);
// h^3
hr[3] = mulmod(hr[2], hr[0], _pp);
// qx = -h^3 -2u1h^2+r^2
uint256 qx = addmod(mulmod(hr[1], hr[1], _pp), _pp - hr[3], _pp);
qx = addmod(qx, _pp - mulmod(2, mulmod(zs[0], hr[2], _pp), _pp), _pp);
// qy = -s1*z1*h^3+r(u1*h^2 -x^3)
uint256 qy = mulmod(hr[1], addmod(mulmod(zs[0], hr[2], _pp), _pp - qx, _pp), _pp);
qy = addmod(qy, _pp - mulmod(zs[1], hr[3], _pp), _pp);
// qz = h*z1*z2
uint256 qz = mulmod(hr[0], mulmod(_z1, _z2, _pp), _pp);
return(qx, qy, qz);
}
/// @dev Doubles a points (x, y, z).
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _pp the modulus
/// @param _aa the a scalar in the curve equation
/// @return (qx, qy, qz) 2P in Jacobian
function jacDouble(
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
if (_z == 0)
return (_x, _y, _z);
uint256[3] memory square;
// We follow the equations described in https://pdfs.semanticscholar.org/5c64/29952e08025a9649c2b0ba32518e9a7fb5c2.pdf Section 5
// Note: there is a bug in the paper regarding the m parameter, M=3*(x1^2)+a*(z1^4)
square[0] = mulmod(_x, _x, _pp); //x1^2
square[1] = mulmod(_y, _y, _pp); //y1^2
square[2] = mulmod(_z, _z, _pp); //z1^2
// s
uint s = mulmod(4, mulmod(_x, square[1], _pp), _pp);
// m
uint m = addmod(mulmod(3, square[0], _pp), mulmod(_aa, mulmod(square[2], square[2], _pp), _pp), _pp);
// qx
uint256 qx = addmod(mulmod(m, m, _pp), _pp - addmod(s, s, _pp), _pp);
// qy = -8*y1^4 + M(S-T)
uint256 qy = addmod(mulmod(m, addmod(s, _pp - qx, _pp), _pp), _pp - mulmod(8, mulmod(square[1], square[1], _pp), _pp), _pp);
// qz = 2*y1*z1
uint256 qz = mulmod(2, mulmod(_y, _z, _pp), _pp);
return (qx, qy, qz);
}
/// @dev Multiply point (x, y, z) times d.
/// @param _d scalar to multiply
/// @param _x coordinate x of P1
/// @param _y coordinate y of P1
/// @param _z coordinate z of P1
/// @param _aa constant of curve
/// @param _pp the modulus
/// @return (qx, qy, qz) d*P1 in Jacobian
function jacMul(
uint256 _d,
uint256 _x,
uint256 _y,
uint256 _z,
uint256 _aa,
uint256 _pp)
internal pure returns (uint256, uint256, uint256)
{
uint256 remaining = _d;
uint256[3] memory point;
point[0] = _x;
point[1] = _y;
point[2] = _z;
uint256 qx = 0;
uint256 qy = 0;
uint256 qz = 1;
if (_d == 0) {
return (qx, qy, qz);
}
// Double and add algorithm
while (remaining != 0) {
if ((remaining & 1) != 0) {
(qx, qy, qz) = jacAdd(
qx,
qy,
qz,
point[0],
point[1],
point[2],
_pp);
}
remaining = remaining / 2;
(point[0], point[1], point[2]) = jacDouble(
point[0],
point[1],
point[2],
_aa,
_pp);
}
return (qx, qy, qz);
}
}
// File: vrf-solidity/contracts/VRF.sol
/**
* @title Verifiable Random Functions (VRF)
* @notice Library verifying VRF proofs using the `Secp256k1` curve and the `SHA256` hash function.
* @dev This library follows the algorithms described in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04) and [RFC6979](https://tools.ietf.org/html/rfc6979).
* It supports the _SECP256K1_SHA256_TAI_ cipher suite, i.e. the aforementioned algorithms using `SHA256` and the `Secp256k1` curve.
* @author Witnet Foundation
*/
library VRF {
/**
* Secp256k1 parameters
*/
// Generator coordinate `x` of the EC curve
uint256 public constant GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798;
// Generator coordinate `y` of the EC curve
uint256 public constant GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8;
// Constant `a` of EC equation
uint256 public constant AA = 0;
// Constant `b` of EC equation
uint256 public constant BB = 7;
// Prime number of the curve
uint256 public constant PP = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F;
// Order of the curve
uint256 public constant NN = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
/// @dev Public key derivation from private key.
/// @param _d The scalar
/// @param _x The coordinate x
/// @param _y The coordinate y
/// @return (qx, qy) The derived point
function derivePoint(uint256 _d, uint256 _x, uint256 _y) internal pure returns (uint256, uint256) {
return EllipticCurve.ecMul(
_d,
_x,
_y,
AA,
PP
);
}
/// @dev Function to derive the `y` coordinate given the `x` coordinate and the parity byte (`0x03` for odd `y` and `0x04` for even `y`).
/// @param _yByte The parity byte following the ec point compressed format
/// @param _x The coordinate `x` of the point
/// @return The coordinate `y` of the point
function deriveY(uint8 _yByte, uint256 _x) internal pure returns (uint256) {
return EllipticCurve.deriveY(
_yByte,
_x,
AA,
BB,
PP);
}
/// @dev Computes the VRF hash output as result of the digest of a ciphersuite-dependent prefix
/// concatenated with the gamma point
/// @param _gammaX The x-coordinate of the gamma EC point
/// @param _gammaY The y-coordinate of the gamma EC point
/// @return The VRF hash ouput as shas256 digest
function gammaToHash(uint256 _gammaX, uint256 _gammaY) internal pure returns (bytes32) {
bytes memory c = abi.encodePacked(
// Cipher suite code (SECP256K1-SHA256-TAI is 0xFE)
uint8(0xFE),
// 0x01
uint8(0x03),
// Compressed Gamma Point
encodePoint(_gammaX, _gammaY));
return sha256(c);
}
/// @dev VRF verification by providing the public key, the message and the VRF proof.
/// This function computes several elliptic curve operations which may lead to extensive gas consumption.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @return true, if VRF proof is valid
function verify(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message) internal pure returns (bool) {
// Step 2: Hash to try and increment (outputs a hashed value, a finite EC point in G)
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
// Step 3: U = s*B - c*Y (where B is the generator)
(uint256 uPointX, uint256 uPointY) = ecMulSubMul(
_proof[3],
GX,
GY,
_proof[2],
_publicKey[0],
_publicKey[1]);
// Step 4: V = s*H - c*Gamma
(uint256 vPointX, uint256 vPointY) = ecMulSubMul(
_proof[3],
hPoint[0],
hPoint[1],
_proof[2],
_proof[0],_proof[1]);
// Step 5: derived c from hash points(...)
bytes16 derivedC = hashPoints(
hPoint[0],
hPoint[1],
_proof[0],
_proof[1],
uPointX,
uPointY,
vPointX,
vPointY);
// Step 6: Check validity c == c'
return uint128(derivedC) == _proof[2];
}
/// @dev VRF fast verification by providing the public key, the message, the VRF proof and several intermediate elliptic curve points that enable the verification shortcut.
/// This function leverages the EVM's `ecrecover` precompile to verify elliptic curve multiplications by decreasing the security from 32 to 20 bytes.
/// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @param _uPoint The `u` EC point defined as `U = s*B - c*Y`
/// @param _vComponents The components required to compute `v` as `V = s*H - c*Gamma`
/// @return true, if VRF proof is valid
function fastVerify(
uint256[2] memory _publicKey,
uint256[4] memory _proof,
bytes memory _message,
uint256[2] memory _uPoint,
uint256[4] memory _vComponents)
internal pure returns (bool)
{
// Step 2: Hash to try and increment -> hashed value, a finite EC point in G
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
// Step 3 & Step 4:
// U = s*B - c*Y (where B is the generator)
// V = s*H - c*Gamma
if (!ecMulSubMulVerify(
_proof[3],
_proof[2],
_publicKey[0],
_publicKey[1],
_uPoint[0],
_uPoint[1]) ||
!ecMulVerify(
_proof[3],
hPoint[0],
hPoint[1],
_vComponents[0],
_vComponents[1]) ||
!ecMulVerify(
_proof[2],
_proof[0],
_proof[1],
_vComponents[2],
_vComponents[3])
)
{
return false;
}
(uint256 vPointX, uint256 vPointY) = EllipticCurve.ecSub(
_vComponents[0],
_vComponents[1],
_vComponents[2],
_vComponents[3],
AA,
PP);
// Step 5: derived c from hash points(...)
bytes16 derivedC = hashPoints(
hPoint[0],
hPoint[1],
_proof[0],
_proof[1],
_uPoint[0],
_uPoint[1],
vPointX,
vPointY);
// Step 6: Check validity c == c'
return uint128(derivedC) == _proof[2];
}
/// @dev Decode VRF proof from bytes
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
function decodeProof(bytes memory _proof) internal pure returns (uint[4] memory) {
require(_proof.length == 81, "Malformed VRF proof");
uint8 gammaSign;
uint256 gammaX;
uint128 c;
uint256 s;
assembly {
gammaSign := mload(add(_proof, 1))
gammaX := mload(add(_proof, 33))
c := mload(add(_proof, 49))
s := mload(add(_proof, 81))
}
uint256 gammaY = deriveY(gammaSign, gammaX);
return [
gammaX,
gammaY,
c,
s];
}
/// @dev Decode EC point from bytes
/// @param _point The EC point as bytes
/// @return The point as `[point-x, point-y]`
function decodePoint(bytes memory _point) internal pure returns (uint[2] memory) {
require(_point.length == 33, "Malformed compressed EC point");
uint8 sign;
uint256 x;
assembly {
sign := mload(add(_point, 1))
x := mload(add(_point, 33))
}
uint256 y = deriveY(sign, x);
return [x, y];
}
/// @dev Compute the parameters (EC points) required for the VRF fast verification function.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`
/// @param _message The message (in bytes) used for computing the VRF
/// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`
function computeFastVerifyParams(uint256[2] memory _publicKey, uint256[4] memory _proof, bytes memory _message)
internal pure returns (uint256[2] memory, uint256[4] memory)
{
// Requirements for Step 3: U = s*B - c*Y (where B is the generator)
uint256[2] memory hPoint;
(hPoint[0], hPoint[1]) = hashToTryAndIncrement(_publicKey, _message);
(uint256 uPointX, uint256 uPointY) = ecMulSubMul(
_proof[3],
GX,
GY,
_proof[2],
_publicKey[0],
_publicKey[1]);
// Requirements for Step 4: V = s*H - c*Gamma
(uint256 sHX, uint256 sHY) = derivePoint(_proof[3], hPoint[0], hPoint[1]);
(uint256 cGammaX, uint256 cGammaY) = derivePoint(_proof[2], _proof[0], _proof[1]);
return (
[uPointX, uPointY],
[
sHX,
sHY,
cGammaX,
cGammaY
]);
}
/// @dev Function to convert a `Hash(PK|DATA)` to a point in the curve as defined in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04).
/// Used in Step 2 of VRF verification function.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`
/// @param _message The message used for computing the VRF
/// @return The hash point in affine cooridnates
function hashToTryAndIncrement(uint256[2] memory _publicKey, bytes memory _message) internal pure returns (uint, uint) {
// Step 1: public key to bytes
// Step 2: V = cipher_suite | 0x01 | public_key_bytes | message | ctr
bytes memory c = abi.encodePacked(
// Cipher suite code (SECP256K1-SHA256-TAI is 0xFE)
uint8(254),
// 0x01
uint8(1),
// Public Key
encodePoint(_publicKey[0], _publicKey[1]),
// Message
_message);
// Step 3: find a valid EC point
// Loop over counter ctr starting at 0x00 and do hash
for (uint8 ctr = 0; ctr < 256; ctr++) {
// Counter update
// c[cLength-1] = byte(ctr);
bytes32 sha = sha256(abi.encodePacked(c, ctr));
// Step 4: arbitraty string to point and check if it is on curve
uint hPointX = uint256(sha);
uint hPointY = deriveY(2, hPointX);
if (EllipticCurve.isOnCurve(
hPointX,
hPointY,
AA,
BB,
PP))
{
// Step 5 (omitted): calculate H (cofactor is 1 on secp256k1)
// If H is not "INVALID" and cofactor > 1, set H = cofactor * H
return (hPointX, hPointY);
}
}
revert("No valid point was found");
}
/// @dev Function to hash a certain set of points as specified in [VRF-draft-04](https://tools.ietf.org/pdf/draft-irtf-cfrg-vrf-04).
/// Used in Step 5 of VRF verification function.
/// @param _hPointX The coordinate `x` of point `H`
/// @param _hPointY The coordinate `y` of point `H`
/// @param _gammaX The coordinate `x` of the point `Gamma`
/// @param _gammaX The coordinate `y` of the point `Gamma`
/// @param _uPointX The coordinate `x` of point `U`
/// @param _uPointY The coordinate `y` of point `U`
/// @param _vPointX The coordinate `x` of point `V`
/// @param _vPointY The coordinate `y` of point `V`
/// @return The first half of the digest of the points using SHA256
function hashPoints(
uint256 _hPointX,
uint256 _hPointY,
uint256 _gammaX,
uint256 _gammaY,
uint256 _uPointX,
uint256 _uPointY,
uint256 _vPointX,
uint256 _vPointY)
internal pure returns (bytes16)
{
bytes memory c = abi.encodePacked(
// Ciphersuite 0xFE
uint8(254),
// Prefix 0x02
uint8(2),
// Points to Bytes
encodePoint(_hPointX, _hPointY),
encodePoint(_gammaX, _gammaY),
encodePoint(_uPointX, _uPointY),
encodePoint(_vPointX, _vPointY)
);
// Hash bytes and truncate
bytes32 sha = sha256(c);
bytes16 half1;
assembly {
let freemem_pointer := mload(0x40)
mstore(add(freemem_pointer,0x00), sha)
half1 := mload(add(freemem_pointer,0x00))
}
return half1;
}
/// @dev Encode an EC point to bytes
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @return The point coordinates as bytes
function encodePoint(uint256 _x, uint256 _y) internal pure returns (bytes memory) {
uint8 prefix = uint8(2 + (_y % 2));
return abi.encodePacked(prefix, _x);
}
/// @dev Substracts two key derivation functionsas `s1*A - s2*B`.
/// @param _scalar1 The scalar `s1`
/// @param _a1 The `x` coordinate of point `A`
/// @param _a2 The `y` coordinate of point `A`
/// @param _scalar2 The scalar `s2`
/// @param _b1 The `x` coordinate of point `B`
/// @param _b2 The `y` coordinate of point `B`
/// @return The derived point in affine cooridnates
function ecMulSubMul(
uint256 _scalar1,
uint256 _a1,
uint256 _a2,
uint256 _scalar2,
uint256 _b1,
uint256 _b2)
internal pure returns (uint256, uint256)
{
(uint256 m1, uint256 m2) = derivePoint(_scalar1, _a1, _a2);
(uint256 n1, uint256 n2) = derivePoint(_scalar2, _b1, _b2);
(uint256 r1, uint256 r2) = EllipticCurve.ecSub(
m1,
m2,
n1,
n2,
AA,
PP);
return (r1, r2);
}
/// @dev Verify an Elliptic Curve multiplication of the form `(qx,qy) = scalar*(x,y)` by using the precompiled `ecrecover` function.
/// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes.
/// Based on the original idea of Vitalik Buterin: https://ethresear.ch/t/you-can-kinda-abuse-ecrecover-to-do-ecmul-in-secp256k1-today/2384/9
/// @param _scalar The scalar of the point multiplication
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @param _qx The coordinate `x` of the multiplication result
/// @param _qy The coordinate `y` of the multiplication result
/// @return true, if first 20 bytes match
function ecMulVerify(
uint256 _scalar,
uint256 _x,
uint256 _y,
uint256 _qx,
uint256 _qy)
internal pure returns(bool)
{
address result = ecrecover(
0,
_y % 2 != 0 ? 28 : 27,
bytes32(_x),
bytes32(mulmod(_scalar, _x, NN)));
return pointToAddress(_qx, _qy) == result;
}
/// @dev Verify an Elliptic Curve operation of the form `Q = scalar1*(gx,gy) - scalar2*(x,y)` by using the precompiled `ecrecover` function, where `(gx,gy)` is the generator of the EC.
/// The usage of the precompiled `ecrecover` function decreases the security from 32 to 20 bytes.
/// Based on SolCrypto library: https://github.com/HarryR/solcrypto
/// @param _scalar1 The scalar of the multiplication of `(gx,gy)`
/// @param _scalar2 The scalar of the multiplication of `(x,y)`
/// @param _x The coordinate `x` of the point to be mutiply by `scalar2`
/// @param _y The coordinate `y` of the point to be mutiply by `scalar2`
/// @param _qx The coordinate `x` of the equation result
/// @param _qy The coordinate `y` of the equation result
/// @return true, if first 20 bytes match
function ecMulSubMulVerify(
uint256 _scalar1,
uint256 _scalar2,
uint256 _x,
uint256 _y,
uint256 _qx,
uint256 _qy)
internal pure returns(bool)
{
uint256 scalar1 = (NN - _scalar1) % NN;
scalar1 = mulmod(scalar1, _x, NN);
uint256 scalar2 = (NN - _scalar2) % NN;
address result = ecrecover(
bytes32(scalar1),
_y % 2 != 0 ? 28 : 27,
bytes32(_x),
bytes32(mulmod(scalar2, _x, NN)));
return pointToAddress(_qx, _qy) == result;
}
/// @dev Gets the address corresponding to the EC point digest (keccak256), i.e. the first 20 bytes of the digest.
/// This function is used for performing a fast EC multiplication verification.
/// @param _x The coordinate `x` of the point
/// @param _y The coordinate `y` of the point
/// @return The address of the EC point digest (keccak256)
function pointToAddress(uint256 _x, uint256 _y)
internal pure returns(address)
{
return address(uint256(keccak256(abi.encodePacked(_x, _y))) & 0x00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
}
}
// File: witnet-ethereum-bridge/contracts/ActiveBridgeSetLib.sol
/**
* @title Active Bridge Set (ABS) library
* @notice This library counts the number of bridges that were active recently.
*/
library ActiveBridgeSetLib {
// Number of Ethereum blocks during which identities can be pushed into a single activity slot
uint8 public constant CLAIM_BLOCK_PERIOD = 8;
// Number of activity slots in the ABS
uint8 public constant ACTIVITY_LENGTH = 100;
struct ActiveBridgeSet {
// Mapping of activity slots with participating identities
mapping (uint16 => address[]) epochIdentities;
// Mapping of identities with their participation count
mapping (address => uint16) identityCount;
// Number of identities in the Active Bridge Set (consolidated during `ACTIVITY_LENGTH`)
uint32 activeIdentities;
// Number of identities for the next activity slot (to be updated in the next activity slot)
uint32 nextActiveIdentities;
// Last used block number during an activity update
uint256 lastBlockNumber;
}
modifier validBlockNumber(uint256 _blockFromArguments, uint256 _blockFromContractState) {
require (_blockFromArguments >= _blockFromContractState, "The provided block is older than the last updated block");
_;
}
/// @dev Updates activity in Witnet without requiring protocol participation.
/// @param _abs The Active Bridge Set structure to be updated.
/// @param _blockNumber The block number up to which the activity should be updated.
function updateActivity(ActiveBridgeSet storage _abs, uint256 _blockNumber)
internal
validBlockNumber(_blockNumber, _abs.lastBlockNumber)
{
(uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber);
// Avoid gas cost if ABS is up to date
require(
updateABS(
_abs,
currentSlot,
lastSlot,
overflow
), "The ABS was already up to date");
_abs.lastBlockNumber = _blockNumber;
}
/// @dev Pushes activity updates through protocol activities (implying insertion of identity).
/// @param _abs The Active Bridge Set structure to be updated.
/// @param _address The address pushing the activity.
/// @param _blockNumber The block number up to which the activity should be updated.
function pushActivity(ActiveBridgeSet storage _abs, address _address, uint256 _blockNumber)
internal
validBlockNumber(_blockNumber, _abs.lastBlockNumber)
returns (bool success)
{
(uint16 currentSlot, uint16 lastSlot, bool overflow) = getSlots(_abs, _blockNumber);
// Update ABS and if it was already up to date, check if identities already counted
if (
updateABS(
_abs,
currentSlot,
lastSlot,
overflow
))
{
_abs.lastBlockNumber = _blockNumber;
} else {
// Check if address was already counted as active identity in this current activity slot
uint256 epochIdsLength = _abs.epochIdentities[currentSlot].length;
for (uint256 i; i < epochIdsLength; i++) {
if (_abs.epochIdentities[currentSlot][i] == _address) {
return false;
}
}
}
// Update current activity slot with identity:
// 1. Add currentSlot to `epochIdentities` with address
// 2. If count = 0, increment by 1 `nextActiveIdentities`
// 3. Increment by 1 the count of the identity
_abs.epochIdentities[currentSlot].push(_address);
if (_abs.identityCount[_address] == 0) {
_abs.nextActiveIdentities++;
}
_abs.identityCount[_address]++;
return true;
}
/// @dev Checks if an address is a member of the ABS.
/// @param _abs The Active Bridge Set structure from the Witnet Requests Board.
/// @param _address The address to check.
/// @return true if address is member of ABS.
function absMembership(ActiveBridgeSet storage _abs, address _address) internal view returns (bool) {
return _abs.identityCount[_address] > 0;
}
/// @dev Gets the slots of the last block seen by the ABS provided and the block number provided.
/// @param _abs The Active Bridge Set structure containing the last block.
/// @param _blockNumber The block number from which to get the current slot.
/// @return (currentSlot, lastSlot, overflow), where overflow implies the block difference > CLAIM_BLOCK_PERIOD* ACTIVITY_LENGTH.
function getSlots(ActiveBridgeSet storage _abs, uint256 _blockNumber) private view returns (uint8, uint8, bool) {
// Get current activity slot number
uint8 currentSlot = uint8((_blockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH);
// Get last actitivy slot number
uint8 lastSlot = uint8((_abs.lastBlockNumber / CLAIM_BLOCK_PERIOD) % ACTIVITY_LENGTH);
// Check if there was an activity slot overflow
// `ACTIVITY_LENGTH` is changed to `uint16` here to ensure the multiplication doesn't overflow silently
bool overflow = (_blockNumber - _abs.lastBlockNumber) >= CLAIM_BLOCK_PERIOD * uint16(ACTIVITY_LENGTH);
return (currentSlot, lastSlot, overflow);
}
/// @dev Updates the provided ABS according to the slots provided.
/// @param _abs The Active Bridge Set to be updated.
/// @param _currentSlot The current slot.
/// @param _lastSlot The last slot seen by the ABS.
/// @param _overflow Whether the current slot has overflown the last slot.
/// @return True if update occurred.
function updateABS(
ActiveBridgeSet storage _abs,
uint16 _currentSlot,
uint16 _lastSlot,
bool _overflow)
private
returns (bool)
{
// If there are more than `ACTIVITY_LENGTH` slots empty => remove entirely the ABS
if (_overflow) {
flushABS(_abs, _lastSlot, _lastSlot);
// If ABS are not up to date => fill previous activity slots with empty activities
} else if (_currentSlot != _lastSlot) {
flushABS(_abs, _currentSlot, _lastSlot);
} else {
return false;
}
return true;
}
/// @dev Flushes the provided ABS record between lastSlot and currentSlot.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _currentSlot The current slot.
function flushABS(ActiveBridgeSet storage _abs, uint16 _currentSlot, uint16 _lastSlot) private {
// For each slot elapsed, remove identities and update `nextActiveIdentities` count
for (uint16 slot = (_lastSlot + 1) % ACTIVITY_LENGTH ; slot != _currentSlot ; slot = (slot + 1) % ACTIVITY_LENGTH) {
flushSlot(_abs, slot);
}
// Update current activity slot
flushSlot(_abs, _currentSlot);
_abs.activeIdentities = _abs.nextActiveIdentities;
}
/// @dev Flushes a slot of the provided ABS.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _slot The slot to be flushed.
function flushSlot(ActiveBridgeSet storage _abs, uint16 _slot) private {
// For a given slot, go through all identities to flush them
uint256 epochIdsLength = _abs.epochIdentities[_slot].length;
for (uint256 id = 0; id < epochIdsLength; id++) {
flushIdentity(_abs, _abs.epochIdentities[_slot][id]);
}
delete _abs.epochIdentities[_slot];
}
/// @dev Decrements the appearance counter of an identity from the provided ABS. If the counter reaches 0, the identity is flushed.
/// @param _abs The Active Bridge Set to be flushed.
/// @param _address The address to be flushed.
function flushIdentity(ActiveBridgeSet storage _abs, address _address) private {
require(absMembership(_abs, _address), "The identity address is already out of the ARS");
// Decrement the count of an identity, and if it reaches 0, delete it and update `nextActiveIdentities`count
_abs.identityCount[_address]--;
if (_abs.identityCount[_address] == 0) {
delete _abs.identityCount[_address];
_abs.nextActiveIdentities--;
}
}
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardInterface.sol
/**
* @title Witnet Requests Board Interface
* @notice Interface of a Witnet Request Board (WRB)
* It defines how to interact with the WRB in order to support:
* - Post and upgrade a data request
* - Read the result of a dr
* @author Witnet Foundation
*/
interface WitnetRequestsBoardInterface {
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256);
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable;
/// @dev Retrieves the DR hash of the id from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DR
function readDrHash (uint256 _id) external view returns(uint256);
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR
function readResult (uint256 _id) external view returns(bytes memory);
/// @notice Verifies if the block relay can be upgraded.
/// @return true if contract is upgradable.
function isUpgradable(address _address) external view returns(bool);
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoard.sol
/**
* @title Witnet Requests Board
* @notice Contract to bridge requests to Witnet.
* @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.
* The result of the requests will be posted back to this contract by the bridge nodes too.
* @author Witnet Foundation
*/
contract WitnetRequestsBoard is WitnetRequestsBoardInterface {
using ActiveBridgeSetLib for ActiveBridgeSetLib.ActiveBridgeSet;
// Expiration period after which a Witnet Request can be claimed again
uint256 public constant CLAIM_EXPIRATION = 13;
struct DataRequest {
bytes dr;
uint256 inclusionReward;
uint256 tallyReward;
bytes result;
// Block number at which the DR was claimed for the last time
uint256 blockNumber;
uint256 drHash;
address payable pkhClaim;
}
// Owner of the Witnet Request Board
address public witnet;
// Block Relay proxy prividing verification functions
BlockRelayProxy public blockRelay;
// Witnet Requests within the board
DataRequest[] public requests;
// Set of recently active bridges
ActiveBridgeSetLib.ActiveBridgeSet public abs;
// Replication factor for Active Bridge Set identities
uint8 public repFactor;
// Event emitted when a new DR is posted
event PostedRequest(address indexed _from, uint256 _id);
// Event emitted when a DR inclusion proof is posted
event IncludedRequest(address indexed _from, uint256 _id);
// Event emitted when a result proof is posted
event PostedResult(address indexed _from, uint256 _id);
// Ensures the reward is not greater than the value
modifier payingEnough(uint256 _value, uint256 _tally) {
require(_value >= _tally, "Transaction value needs to be equal or greater than tally reward");
_;
}
// Ensures the poe is valid
modifier poeValid(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers) {
require(
verifyPoe(
_poe,
_publicKey,
_uPoint,
_vPointHelpers),
"Not a valid PoE");
_;
}
// Ensures signature (sign(msg.sender)) is valid
modifier validSignature(
uint256[2] memory _publicKey,
bytes memory addrSignature) {
require(verifySig(abi.encodePacked(msg.sender), _publicKey, addrSignature), "Not a valid signature");
_;
}
// Ensures the DR inclusion proof has not been reported yet
modifier drNotIncluded(uint256 _id) {
require(requests[_id].drHash == 0, "DR already included");
_;
}
// Ensures the DR inclusion has been already reported
modifier drIncluded(uint256 _id) {
require(requests[_id].drHash != 0, "DR not yet included");
_;
}
// Ensures the result has not been reported yet
modifier resultNotIncluded(uint256 _id) {
require(requests[_id].result.length == 0, "Result already included");
_;
}
// Ensures the VRF is valid
modifier vrfValid(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers) virtual {
require(
VRF.fastVerify(
_publicKey,
_poe,
getLastBeacon(),
_uPoint,
_vPointHelpers),
"Not a valid VRF");
_;
}
// Ensures the address belongs to the active bridge set
modifier absMember(address _address) {
require(abs.absMembership(_address), "Not a member of the ABS");
_;
}
/**
* @notice Include an address to specify the Witnet Block Relay and a replication factor.
* @param _blockRelayAddress BlockRelayProxy address.
* @param _repFactor replication factor.
*/
constructor(address _blockRelayAddress, uint8 _repFactor) public {
blockRelay = BlockRelayProxy(_blockRelayAddress);
witnet = msg.sender;
// Insert an empty request so as to initialize the requests array with length > 0
DataRequest memory request;
requests.push(request);
repFactor = _repFactor;
}
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _serialized The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _serialized, uint256 _tallyReward)
external
payable
payingEnough(msg.value, _tallyReward)
override
returns(uint256)
{
// The initial length of the `requests` array will become the ID of the request for everything related to the WRB
uint256 id = requests.length;
// Create a new `DataRequest` object and initialize all the non-default fields
DataRequest memory request;
request.dr = _serialized;
request.inclusionReward = SafeMath.sub(msg.value, _tallyReward);
request.tallyReward = _tallyReward;
// Push the new request into the contract state
requests.push(request);
// Let observers know that a new request has been posted
emit PostedRequest(msg.sender, id);
return id;
}
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward)
external
payable
payingEnough(msg.value, _tallyReward)
resultNotIncluded(_id)
override
{
if (requests[_id].drHash != 0) {
require(
msg.value == _tallyReward,
"Txn value should equal result reward argument (request reward already paid)"
);
requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward);
} else {
requests[_id].inclusionReward = SafeMath.add(requests[_id].inclusionReward, msg.value - _tallyReward);
requests[_id].tallyReward = SafeMath.add(requests[_id].tallyReward, _tallyReward);
}
}
/// @dev Checks if the data requests from a list are claimable or not.
/// @param _ids The list of data request identifiers to be checked.
/// @return An array of booleans indicating if data requests are claimable or not.
function checkDataRequestsClaimability(uint256[] calldata _ids) external view returns (bool[] memory) {
uint256 idsLength = _ids.length;
bool[] memory validIds = new bool[](idsLength);
for (uint i = 0; i < idsLength; i++) {
uint256 index = _ids[i];
validIds[i] = (dataRequestCanBeClaimed(requests[index])) &&
requests[index].drHash == 0 &&
index < requests.length &&
requests[index].result.length == 0;
}
return validIds;
}
/// @dev Presents a proof of inclusion to prove that the request was posted into Witnet so as to unlock the inclusion reward that was put aside for the claiming identity (public key hash).
/// @param _id The unique identifier of the data request.
/// @param _poi A proof of inclusion proving that the data request appears listed in one recent block in Witnet.
/// @param _index The index in the merkle tree.
/// @param _blockHash The hash of the block in which the data request was inserted.
/// @param _epoch The epoch in which the blockHash was created.
function reportDataRequestInclusion(
uint256 _id,
uint256[] calldata _poi,
uint256 _index,
uint256 _blockHash,
uint256 _epoch)
external
drNotIncluded(_id)
{
// Check the data request has been claimed
require(dataRequestCanBeClaimed(requests[_id]) == false, "Data Request has not yet been claimed");
uint256 drOutputHash = uint256(sha256(requests[_id].dr));
uint256 drHash = uint256(sha256(abi.encodePacked(drOutputHash, _poi[0])));
// Update the state upon which this function depends before the external call
requests[_id].drHash = drHash;
require(
blockRelay.verifyDrPoi(
_poi,
_blockHash,
_epoch,
_index,
drOutputHash), "Invalid PoI");
requests[_id].pkhClaim.transfer(requests[_id].inclusionReward);
// Push requests[_id].pkhClaim to abs
abs.pushActivity(requests[_id].pkhClaim, block.number);
emit IncludedRequest(msg.sender, _id);
}
/// @dev Reports the result of a data request in Witnet.
/// @param _id The unique identifier of the data request.
/// @param _poi A proof of inclusion proving that the data in _result has been acknowledged by the Witnet network as being the final result for the data request by putting in a tally transaction inside a Witnet block.
/// @param _index The position of the tally transaction in the tallies-only merkle tree in the Witnet block.
/// @param _blockHash The hash of the block in which the result (tally) was inserted.
/// @param _epoch The epoch in which the blockHash was created.
/// @param _result The result itself as bytes.
function reportResult(
uint256 _id,
uint256[] calldata _poi,
uint256 _index,
uint256 _blockHash,
uint256 _epoch,
bytes calldata _result)
external
drIncluded(_id)
resultNotIncluded(_id)
absMember(msg.sender)
{
// Ensures the result byes do not have zero length
// This would not be a valid encoding with CBOR and could trigger a reentrancy attack
require(_result.length != 0, "Result has zero length");
// Update the state upon which this function depends before the external call
requests[_id].result = _result;
uint256 resHash = uint256(sha256(abi.encodePacked(requests[_id].drHash, _result)));
require(
blockRelay.verifyTallyPoi(
_poi,
_blockHash,
_epoch,
_index,
resHash), "Invalid PoI");
msg.sender.transfer(requests[_id].tallyReward);
emit PostedResult(msg.sender, _id);
}
/// @dev Retrieves the bytes of the serialization of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the data request as bytes.
function readDataRequest(uint256 _id) external view returns(bytes memory) {
require(requests.length > _id, "Id not found");
return requests[_id].dr;
}
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR
function readResult(uint256 _id) external view override returns(bytes memory) {
require(requests.length > _id, "Id not found");
return requests[_id].result;
}
/// @dev Retrieves hash of the data request transaction in Witnet.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DataRequest transaction in Witnet.
function readDrHash(uint256 _id) external view override returns(uint256) {
require(requests.length > _id, "Id not found");
return requests[_id].drHash;
}
/// @dev Returns the number of data requests in the WRB.
/// @return the number of data requests in the WRB.
function requestsCount() external view returns(uint256) {
return requests.length;
}
/// @notice Wrapper around the decodeProof from VRF library.
/// @dev Decode VRF proof from bytes.
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
/// @return The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
function decodeProof(bytes calldata _proof) external pure returns (uint[4] memory) {
return VRF.decodeProof(_proof);
}
/// @notice Wrapper around the decodePoint from VRF library.
/// @dev Decode EC point from bytes.
/// @param _point The EC point as bytes.
/// @return The point as `[point-x, point-y]`.
function decodePoint(bytes calldata _point) external pure returns (uint[2] memory) {
return VRF.decodePoint(_point);
}
/// @dev Wrapper around the computeFastVerifyParams from VRF library.
/// @dev Compute the parameters (EC points) required for the VRF fast verification function..
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`.
/// @param _proof The VRF proof as an array composed of `[gamma-x, gamma-y, c, s]`.
/// @param _message The message (in bytes) used for computing the VRF.
/// @return The fast verify required parameters as the tuple `([uPointX, uPointY], [sHX, sHY, cGammaX, cGammaY])`.
function computeFastVerifyParams(uint256[2] calldata _publicKey, uint256[4] calldata _proof, bytes calldata _message)
external pure returns (uint256[2] memory, uint256[4] memory)
{
return VRF.computeFastVerifyParams(_publicKey, _proof, _message);
}
/// @dev Updates the ABS activity with the block number provided.
/// @param _blockNumber update the ABS until this block number.
function updateAbsActivity(uint256 _blockNumber) external {
require (_blockNumber <= block.number, "The provided block number has not been reached");
abs.updateActivity(_blockNumber);
}
/// @dev Verifies if the contract is upgradable.
/// @return true if the contract upgradable.
function isUpgradable(address _address) external view override returns(bool) {
if (_address == witnet) {
return true;
}
return false;
}
/// @dev Claim drs to be posted to Witnet by the node.
/// @param _ids Data request ids to be claimed.
/// @param _poe PoE claiming eligibility.
/// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y.
/// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma.
function claimDataRequests(
uint256[] memory _ids,
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers,
bytes memory addrSignature)
public
validSignature(_publicKey, addrSignature)
poeValid(_poe,_publicKey, _uPoint,_vPointHelpers)
returns(bool)
{
for (uint i = 0; i < _ids.length; i++) {
require(
dataRequestCanBeClaimed(requests[_ids[i]]),
"One of the listed data requests was already claimed"
);
requests[_ids[i]].pkhClaim = msg.sender;
requests[_ids[i]].blockNumber = block.number;
}
return true;
}
/// @dev Read the beacon of the last block inserted.
/// @return bytes to be signed by the node as PoE.
function getLastBeacon() public view virtual returns(bytes memory) {
return blockRelay.getLastBeacon();
}
/// @dev Claim drs to be posted to Witnet by the node.
/// @param _poe PoE claiming eligibility.
/// @param _publicKey The public key as an array composed of `[pubKey-x, pubKey-y]`.
/// @param _uPoint uPoint coordinates as [uPointX, uPointY] corresponding to U = s*B - c*Y.
/// @param _vPointHelpers helpers for calculating the V point as [(s*H)X, (s*H)Y, cGammaX, cGammaY]. V = s*H + cGamma.
function verifyPoe(
uint256[4] memory _poe,
uint256[2] memory _publicKey,
uint256[2] memory _uPoint,
uint256[4] memory _vPointHelpers)
internal
view
vrfValid(_poe,_publicKey, _uPoint,_vPointHelpers)
returns(bool)
{
uint256 vrf = uint256(VRF.gammaToHash(_poe[0], _poe[1]));
// True if vrf/(2^{256} -1) <= repFactor/abs.activeIdentities
if (abs.activeIdentities < repFactor) {
return true;
}
// We rewrote it as vrf <= ((2^{256} -1)/abs.activeIdentities)*repFactor to gain efficiency
if (vrf <= ((~uint256(0)/abs.activeIdentities)*repFactor)) {
return true;
}
return false;
}
/// @dev Verifies the validity of a signature.
/// @param _message message to be verified.
/// @param _publicKey public key of the signer as `[pubKey-x, pubKey-y]`.
/// @param _addrSignature the signature to verify asas r||s||v.
/// @return true or false depending the validity.
function verifySig(
bytes memory _message,
uint256[2] memory _publicKey,
bytes memory _addrSignature)
internal
pure
returns(bool)
{
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(_addrSignature, 0x20))
s := mload(add(_addrSignature, 0x40))
v := byte(0, mload(add(_addrSignature, 0x60)))
}
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return false;
}
if (v != 0 && v != 1) {
return false;
}
v = 28 - v;
bytes32 msgHash = sha256(_message);
address hashedKey = VRF.pointToAddress(_publicKey[0], _publicKey[1]);
return ecrecover(
msgHash,
v,
r,
s) == hashedKey;
}
function dataRequestCanBeClaimed(DataRequest memory _request) private view returns (bool) {
return
(_request.blockNumber == 0 || block.number - _request.blockNumber > CLAIM_EXPIRATION) &&
_request.drHash == 0 &&
_request.result.length == 0;
}
}
// File: witnet-ethereum-bridge/contracts/WitnetRequestsBoardProxy.sol
/**
* @title Block Relay Proxy
* @notice Contract to act as a proxy between the Witnet Bridge Interface and the Block Relay.
* @author Witnet Foundation
*/
contract WitnetRequestsBoardProxy {
// Address of the Witnet Request Board contract that is currently being used
address public witnetRequestsBoardAddress;
// Struct if the information of each controller
struct ControllerInfo {
// Address of the Controller
address controllerAddress;
// The lastId of the previous Controller
uint256 lastId;
}
// Last id of the WRB controller
uint256 internal currentLastId;
// Instance of the current WitnetRequestBoard
WitnetRequestsBoardInterface internal witnetRequestsBoardInstance;
// Array with the controllers that have been used in the Proxy
ControllerInfo[] internal controllers;
modifier notIdentical(address _newAddress) {
require(_newAddress != witnetRequestsBoardAddress, "The provided Witnet Requests Board instance address is already in use");
_;
}
/**
* @notice Include an address to specify the Witnet Request Board.
* @param _witnetRequestsBoardAddress WitnetRequestBoard address.
*/
constructor(address _witnetRequestsBoardAddress) public {
// Initialize the first epoch pointing to the first controller
controllers.push(ControllerInfo({controllerAddress: _witnetRequestsBoardAddress, lastId: 0}));
witnetRequestsBoardAddress = _witnetRequestsBoardAddress;
witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_witnetRequestsBoardAddress);
}
/// @dev Posts a data request into the WRB in expectation that it will be relayed and resolved in Witnet with a total reward that equals to msg.value.
/// @param _dr The bytes corresponding to the Protocol Buffers serialization of the data request output.
/// @param _tallyReward The amount of value that will be detracted from the transaction value and reserved for rewarding the reporting of the final result (aka tally) of the data request.
/// @return The unique identifier of the data request.
function postDataRequest(bytes calldata _dr, uint256 _tallyReward) external payable returns(uint256) {
uint256 n = controllers.length;
uint256 offset = controllers[n - 1].lastId;
// Update the currentLastId with the id in the controller plus the offSet
currentLastId = witnetRequestsBoardInstance.postDataRequest{value: msg.value}(_dr, _tallyReward) + offset;
return currentLastId;
}
/// @dev Increments the rewards of a data request by adding more value to it. The new request reward will be increased by msg.value minus the difference between the former tally reward and the new tally reward.
/// @param _id The unique identifier of the data request.
/// @param _tallyReward The new tally reward. Needs to be equal or greater than the former tally reward.
function upgradeDataRequest(uint256 _id, uint256 _tallyReward) external payable {
address wrbAddress;
uint256 wrbOffset;
(wrbAddress, wrbOffset) = getController(_id);
return witnetRequestsBoardInstance.upgradeDataRequest{value: msg.value}(_id - wrbOffset, _tallyReward);
}
/// @dev Retrieves the DR hash of the id from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The hash of the DR.
function readDrHash (uint256 _id)
external
view
returns(uint256)
{
// Get the address and the offset of the corresponding to id
address wrbAddress;
uint256 offsetWrb;
(wrbAddress, offsetWrb) = getController(_id);
// Return the result of the DR readed in the corresponding Controller with its own id
WitnetRequestsBoardInterface wrbWithDrHash;
wrbWithDrHash = WitnetRequestsBoardInterface(wrbAddress);
uint256 drHash = wrbWithDrHash.readDrHash(_id - offsetWrb);
return drHash;
}
/// @dev Retrieves the result (if already available) of one data request from the WRB.
/// @param _id The unique identifier of the data request.
/// @return The result of the DR.
function readResult(uint256 _id) external view returns(bytes memory) {
// Get the address and the offset of the corresponding to id
address wrbAddress;
uint256 offSetWrb;
(wrbAddress, offSetWrb) = getController(_id);
// Return the result of the DR in the corresponding Controller with its own id
WitnetRequestsBoardInterface wrbWithResult;
wrbWithResult = WitnetRequestsBoardInterface(wrbAddress);
return wrbWithResult.readResult(_id - offSetWrb);
}
/// @notice Upgrades the Witnet Requests Board if the current one is upgradeable.
/// @param _newAddress address of the new block relay to upgrade.
function upgradeWitnetRequestsBoard(address _newAddress) public notIdentical(_newAddress) {
// Require the WRB is upgradable
require(witnetRequestsBoardInstance.isUpgradable(msg.sender), "The upgrade has been rejected by the current implementation");
// Map the currentLastId to the corresponding witnetRequestsBoardAddress and add it to controllers
controllers.push(ControllerInfo({controllerAddress: _newAddress, lastId: currentLastId}));
// Upgrade the WRB
witnetRequestsBoardAddress = _newAddress;
witnetRequestsBoardInstance = WitnetRequestsBoardInterface(_newAddress);
}
/// @notice Gets the controller from an Id.
/// @param _id id of a Data Request from which we get the controller.
function getController(uint256 _id) internal view returns(address _controllerAddress, uint256 _offset) {
// Check id is bigger than 0
require(_id > 0, "Non-existent controller for id 0");
uint256 n = controllers.length;
// If the id is bigger than the lastId of a Controller, read the result in that Controller
for (uint i = n; i > 0; i--) {
if (_id > controllers[i - 1].lastId) {
return (controllers[i - 1].controllerAddress, controllers[i - 1].lastId);
}
}
}
}
// File: witnet-ethereum-bridge/contracts/BufferLib.sol
/**
* @title A convenient wrapper around the `bytes memory` type that exposes a buffer-like interface
* @notice The buffer has an inner cursor that tracks the final offset of every read, i.e. any subsequent read will
* start with the byte that goes right after the last one in the previous read.
* @dev `uint32` is used here for `cursor` because `uint16` would only enable seeking up to 8KB, which could in some
* theoretical use cases be exceeded. Conversely, `uint32` supports up to 512MB, which cannot credibly be exceeded.
*/
library BufferLib {
struct Buffer {
bytes data;
uint32 cursor;
}
// Ensures we access an existing index in an array
modifier notOutOfBounds(uint32 index, uint256 length) {
require(index < length, "Tried to read from a consumed Buffer (must rewind it first)");
_;
}
/**
* @notice Read and consume a certain amount of bytes from the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _length How many bytes to read and consume from the buffer.
* @return A `bytes memory` containing the first `_length` bytes from the buffer, counting from the cursor position.
*/
function read(Buffer memory _buffer, uint32 _length) internal pure returns (bytes memory) {
// Make sure not to read out of the bounds of the original bytes
require(_buffer.cursor + _length <= _buffer.data.length, "Not enough bytes in buffer when reading");
// Create a new `bytes memory destination` value
bytes memory destination = new bytes(_length);
bytes memory source = _buffer.data;
uint32 offset = _buffer.cursor;
// Get raw pointers for source and destination
uint sourcePointer;
uint destinationPointer;
assembly {
sourcePointer := add(add(source, 32), offset)
destinationPointer := add(destination, 32)
}
// Copy `_length` bytes from source to destination
memcpy(destinationPointer, sourcePointer, uint(_length));
// Move the cursor forward by `_length` bytes
seek(_buffer, _length, true);
return destination;
}
/**
* @notice Read and consume the next byte from the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The next byte in the buffer counting from the cursor position.
*/
function next(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (byte) {
// Return the byte at the position marked by the cursor and advance the cursor all at once
return _buffer.data[_buffer.cursor++];
}
/**
* @notice Move the inner cursor of the buffer to a relative or absolute position.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _offset How many bytes to move the cursor forward.
* @param _relative Whether to count `_offset` from the last position of the cursor (`true`) or the beginning of the
* buffer (`true`).
* @return The final position of the cursor (will equal `_offset` if `_relative` is `false`).
*/
// solium-disable-next-line security/no-assign-params
function seek(Buffer memory _buffer, uint32 _offset, bool _relative) internal pure returns (uint32) {
// Deal with relative offsets
if (_relative) {
require(_offset + _buffer.cursor > _offset, "Integer overflow when seeking");
_offset += _buffer.cursor;
}
// Make sure not to read out of the bounds of the original bytes
require(_offset <= _buffer.data.length, "Not enough bytes in buffer when seeking");
_buffer.cursor = _offset;
return _buffer.cursor;
}
/**
* @notice Move the inner cursor a number of bytes forward.
* @dev This is a simple wrapper around the relative offset case of `seek()`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @param _relativeOffset How many bytes to move the cursor forward.
* @return The final position of the cursor.
*/
function seek(Buffer memory _buffer, uint32 _relativeOffset) internal pure returns (uint32) {
return seek(_buffer, _relativeOffset, true);
}
/**
* @notice Move the inner cursor back to the first byte in the buffer.
* @param _buffer An instance of `BufferLib.Buffer`.
*/
function rewind(Buffer memory _buffer) internal pure {
_buffer.cursor = 0;
}
/**
* @notice Read and consume the next byte from the buffer as an `uint8`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint8` value of the next byte in the buffer counting from the cursor position.
*/
function readUint8(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor, _buffer.data.length) returns (uint8) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint8 value;
assembly {
value := mload(add(add(bytesValue, 1), offset))
}
_buffer.cursor++;
return value;
}
/**
* @notice Read and consume the next 2 bytes from the buffer as an `uint16`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint16` value of the next 2 bytes in the buffer counting from the cursor position.
*/
function readUint16(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 1, _buffer.data.length) returns (uint16) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint16 value;
assembly {
value := mload(add(add(bytesValue, 2), offset))
}
_buffer.cursor += 2;
return value;
}
/**
* @notice Read and consume the next 4 bytes from the buffer as an `uint32`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position.
*/
function readUint32(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 3, _buffer.data.length) returns (uint32) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint32 value;
assembly {
value := mload(add(add(bytesValue, 4), offset))
}
_buffer.cursor += 4;
return value;
}
/**
* @notice Read and consume the next 8 bytes from the buffer as an `uint64`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint64` value of the next 8 bytes in the buffer counting from the cursor position.
*/
function readUint64(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 7, _buffer.data.length) returns (uint64) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint64 value;
assembly {
value := mload(add(add(bytesValue, 8), offset))
}
_buffer.cursor += 8;
return value;
}
/**
* @notice Read and consume the next 16 bytes from the buffer as an `uint128`.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint128` value of the next 16 bytes in the buffer counting from the cursor position.
*/
function readUint128(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 15, _buffer.data.length) returns (uint128) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint128 value;
assembly {
value := mload(add(add(bytesValue, 16), offset))
}
_buffer.cursor += 16;
return value;
}
/**
* @notice Read and consume the next 32 bytes from the buffer as an `uint256`.
* @return The `uint256` value of the next 32 bytes in the buffer counting from the cursor position.
* @param _buffer An instance of `BufferLib.Buffer`.
*/
function readUint256(Buffer memory _buffer) internal pure notOutOfBounds(_buffer.cursor + 31, _buffer.data.length) returns (uint256) {
bytes memory bytesValue = _buffer.data;
uint32 offset = _buffer.cursor;
uint256 value;
assembly {
value := mload(add(add(bytesValue, 32), offset))
}
_buffer.cursor += 32;
return value;
}
/**
* @notice Read and consume the next 2 bytes from the buffer as an IEEE 754-2008 floating point number enclosed in an
* `int32`.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `float16`
* use cases. In other words, the integer output of this method is 10,000 times the actual value. The input bytes are
* expected to follow the 16-bit base-2 format (a.k.a. `binary16`) in the IEEE 754-2008 standard.
* @param _buffer An instance of `BufferLib.Buffer`.
* @return The `uint32` value of the next 4 bytes in the buffer counting from the cursor position.
*/
function readFloat16(Buffer memory _buffer) internal pure returns (int32) {
uint32 bytesValue = readUint16(_buffer);
// Get bit at position 0
uint32 sign = bytesValue & 0x8000;
// Get bits 1 to 5, then normalize to the [-14, 15] range so as to counterweight the IEEE 754 exponent bias
int32 exponent = (int32(bytesValue & 0x7c00) >> 10) - 15;
// Get bits 6 to 15
int32 significand = int32(bytesValue & 0x03ff);
// Add 1024 to the fraction if the exponent is 0
if (exponent == 15) {
significand |= 0x400;
}
// Compute `2 ^ exponent · (1 + fraction / 1024)`
int32 result = 0;
if (exponent >= 0) {
result = int32(((1 << uint256(exponent)) * 10000 * (uint256(significand) | 0x400)) >> 10);
} else {
result = int32((((uint256(significand) | 0x400) * 10000) / (1 << uint256(- exponent))) >> 10);
}
// Make the result negative if the sign bit is not 0
if (sign != 0) {
result *= - 1;
}
return result;
}
/**
* @notice Copy bytes from one memory address into another.
* @dev This function was borrowed from Nick Johnson's `solidity-stringutils` lib, and reproduced here under the terms
* of [Apache License 2.0](https://github.com/Arachnid/solidity-stringutils/blob/master/LICENSE).
* @param _dest Address of the destination memory.
* @param _src Address to the source memory.
* @param _len How many bytes to copy.
*/
// solium-disable-next-line security/no-assign-params
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))
}
}
}
// File: witnet-ethereum-bridge/contracts/CBOR.sol
/**
* @title A minimalistic implementation of “RFC 7049 Concise Binary Object Representation”
* @notice This library leverages a buffer-like structure for step-by-step decoding of bytes so as to minimize
* the gas cost of decoding them into a useful native type.
* @dev Most of the logic has been borrowed from Patrick Gansterer’s cbor.js library: https://github.com/paroga/cbor-js
* TODO: add support for Array (majorType = 4)
* TODO: add support for Map (majorType = 5)
* TODO: add support for Float32 (majorType = 7, additionalInformation = 26)
* TODO: add support for Float64 (majorType = 7, additionalInformation = 27)
*/
library CBOR {
using BufferLib for BufferLib.Buffer;
uint64 constant internal UINT64_MAX = ~uint64(0);
struct Value {
BufferLib.Buffer buffer;
uint8 initialByte;
uint8 majorType;
uint8 additionalInformation;
uint64 len;
uint64 tag;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `bytes` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as a `bytes` value.
*/
function decodeBytes(Value memory _cborValue) public pure returns(bytes memory) {
_cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation);
if (_cborValue.len == UINT64_MAX) {
bytes memory bytesData;
// These checks look repetitive but the equivalent loop would be more expensive.
uint32 itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType));
if (itemLength < UINT64_MAX) {
bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength));
itemLength = uint32(readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType));
if (itemLength < UINT64_MAX) {
bytesData = abi.encodePacked(bytesData, _cborValue.buffer.read(itemLength));
}
}
return bytesData;
} else {
return _cborValue.buffer.read(uint32(_cborValue.len));
}
}
/**
* @notice Decode a `CBOR.Value` structure into a `fixed16` value.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`
* use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128` value.
*/
function decodeFixed16(Value memory _cborValue) public pure returns(int32) {
require(_cborValue.majorType == 7, "Tried to read a `fixed` value from a `CBOR.Value` with majorType != 7");
require(_cborValue.additionalInformation == 25, "Tried to read `fixed16` from a `CBOR.Value` with additionalInformation != 25");
return _cborValue.buffer.readFloat16();
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128[]` value whose inner values follow the same convention.
* as explained in `decodeFixed16`.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128[]` value.
*/
function decodeFixed16Array(Value memory _cborValue) public pure returns(int128[] memory) {
require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
int128[] memory array = new int128[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeFixed16(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128` value.
*/
function decodeInt128(Value memory _cborValue) public pure returns(int128) {
if (_cborValue.majorType == 1) {
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
return int128(-1) - int128(length);
} else if (_cborValue.majorType == 0) {
// Any `uint64` can be safely casted to `int128`, so this method supports majorType 1 as well so as to have offer
// a uniform API for positive and negative numbers
return int128(decodeUint64(_cborValue));
}
revert("Tried to read `int128` from a `CBOR.Value` with majorType not 0 or 1");
}
/**
* @notice Decode a `CBOR.Value` structure into a native `int128[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `int128[]` value.
*/
function decodeInt128Array(Value memory _cborValue) public pure returns(int128[] memory) {
require(_cborValue.majorType == 4, "Tried to read `int128[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
int128[] memory array = new int128[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeInt128(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `string` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as a `string` value.
*/
function decodeString(Value memory _cborValue) public pure returns(string memory) {
_cborValue.len = readLength(_cborValue.buffer, _cborValue.additionalInformation);
if (_cborValue.len == UINT64_MAX) {
bytes memory textData;
bool done;
while (!done) {
uint64 itemLength = readIndefiniteStringLength(_cborValue.buffer, _cborValue.majorType);
if (itemLength < UINT64_MAX) {
textData = abi.encodePacked(textData, readText(_cborValue.buffer, itemLength / 4));
} else {
done = true;
}
}
return string(textData);
} else {
return string(readText(_cborValue.buffer, _cborValue.len));
}
}
/**
* @notice Decode a `CBOR.Value` structure into a native `string[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `string[]` value.
*/
function decodeStringArray(Value memory _cborValue) public pure returns(string[] memory) {
require(_cborValue.majorType == 4, "Tried to read `string[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
string[] memory array = new string[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeString(item);
}
return array;
}
/**
* @notice Decode a `CBOR.Value` structure into a native `uint64` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `uint64` value.
*/
function decodeUint64(Value memory _cborValue) public pure returns(uint64) {
require(_cborValue.majorType == 0, "Tried to read `uint64` from a `CBOR.Value` with majorType != 0");
return readLength(_cborValue.buffer, _cborValue.additionalInformation);
}
/**
* @notice Decode a `CBOR.Value` structure into a native `uint64[]` value.
* @param _cborValue An instance of `CBOR.Value`.
* @return The value represented by the input, as an `uint64[]` value.
*/
function decodeUint64Array(Value memory _cborValue) public pure returns(uint64[] memory) {
require(_cborValue.majorType == 4, "Tried to read `uint64[]` from a `CBOR.Value` with majorType != 4");
uint64 length = readLength(_cborValue.buffer, _cborValue.additionalInformation);
require(length < UINT64_MAX, "Indefinite-length CBOR arrays are not supported");
uint64[] memory array = new uint64[](length);
for (uint64 i = 0; i < length; i++) {
Value memory item = valueFromBuffer(_cborValue.buffer);
array[i] = decodeUint64(item);
}
return array;
}
/**
* @notice Decode a CBOR.Value structure from raw bytes.
* @dev This is the main factory for CBOR.Value instances, which can be later decoded into native EVM types.
* @param _cborBytes Raw bytes representing a CBOR-encoded value.
* @return A `CBOR.Value` instance containing a partially decoded value.
*/
function valueFromBytes(bytes memory _cborBytes) public pure returns(Value memory) {
BufferLib.Buffer memory buffer = BufferLib.Buffer(_cborBytes, 0);
return valueFromBuffer(buffer);
}
/**
* @notice Decode a CBOR.Value structure from raw bytes.
* @dev This is an alternate factory for CBOR.Value instances, which can be later decoded into native EVM types.
* @param _buffer A Buffer structure representing a CBOR-encoded value.
* @return A `CBOR.Value` instance containing a partially decoded value.
*/
function valueFromBuffer(BufferLib.Buffer memory _buffer) public pure returns(Value memory) {
require(_buffer.data.length > 0, "Found empty buffer when parsing CBOR value");
uint8 initialByte;
uint8 majorType = 255;
uint8 additionalInformation;
uint64 length;
uint64 tag = UINT64_MAX;
bool isTagged = true;
while (isTagged) {
// Extract basic CBOR properties from input bytes
initialByte = _buffer.readUint8();
majorType = initialByte >> 5;
additionalInformation = initialByte & 0x1f;
// Early CBOR tag parsing.
if (majorType == 6) {
tag = readLength(_buffer, additionalInformation);
} else {
isTagged = false;
}
}
require(majorType <= 7, "Invalid CBOR major type");
return CBOR.Value(
_buffer,
initialByte,
majorType,
additionalInformation,
length,
tag);
}
// Reads the length of the next CBOR item from a buffer, consuming a different number of bytes depending on the
// value of the `additionalInformation` argument.
function readLength(BufferLib.Buffer memory _buffer, uint8 additionalInformation) private pure returns(uint64) {
if (additionalInformation < 24) {
return additionalInformation;
}
if (additionalInformation == 24) {
return _buffer.readUint8();
}
if (additionalInformation == 25) {
return _buffer.readUint16();
}
if (additionalInformation == 26) {
return _buffer.readUint32();
}
if (additionalInformation == 27) {
return _buffer.readUint64();
}
if (additionalInformation == 31) {
return UINT64_MAX;
}
revert("Invalid length encoding (non-existent additionalInformation value)");
}
// Read the length of a CBOR indifinite-length item (arrays, maps, byte strings and text) from a buffer, consuming
// as many bytes as specified by the first byte.
function readIndefiniteStringLength(BufferLib.Buffer memory _buffer, uint8 majorType) private pure returns(uint64) {
uint8 initialByte = _buffer.readUint8();
if (initialByte == 0xff) {
return UINT64_MAX;
}
uint64 length = readLength(_buffer, initialByte & 0x1f);
require(length < UINT64_MAX && (initialByte >> 5) == majorType, "Invalid indefinite length");
return length;
}
// Read a text string of a given length from a buffer. Returns a `bytes memory` value for the sake of genericness,
// but it can be easily casted into a string with `string(result)`.
// solium-disable-next-line security/no-assign-params
function readText(BufferLib.Buffer memory _buffer, uint64 _length) private pure returns(bytes memory) {
bytes memory result;
for (uint64 index = 0; index < _length; index++) {
uint8 value = _buffer.readUint8();
if (value & 0x80 != 0) {
if (value < 0xe0) {
value = (value & 0x1f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 1;
} else if (value < 0xf0) {
value = (value & 0x0f) << 12 |
(_buffer.readUint8() & 0x3f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 2;
} else {
value = (value & 0x0f) << 18 |
(_buffer.readUint8() & 0x3f) << 12 |
(_buffer.readUint8() & 0x3f) << 6 |
(_buffer.readUint8() & 0x3f);
_length -= 3;
}
}
result = abi.encodePacked(result, value);
}
return result;
}
}
// File: witnet-ethereum-bridge/contracts/Witnet.sol
/**
* @title A library for decoding Witnet request results
* @notice The library exposes functions to check the Witnet request success.
* and retrieve Witnet results from CBOR values into solidity types.
*/
library Witnet {
using CBOR for CBOR.Value;
/*
STRUCTS
*/
struct Result {
bool success;
CBOR.Value cborValue;
}
/*
ENUMS
*/
enum ErrorCodes {
// 0x00: Unknown error. Something went really bad!
Unknown,
// Script format errors
/// 0x01: At least one of the source scripts is not a valid CBOR-encoded value.
SourceScriptNotCBOR,
/// 0x02: The CBOR value decoded from a source script is not an Array.
SourceScriptNotArray,
/// 0x03: The Array value decoded form a source script is not a valid RADON script.
SourceScriptNotRADON,
/// Unallocated
ScriptFormat0x04,
ScriptFormat0x05,
ScriptFormat0x06,
ScriptFormat0x07,
ScriptFormat0x08,
ScriptFormat0x09,
ScriptFormat0x0A,
ScriptFormat0x0B,
ScriptFormat0x0C,
ScriptFormat0x0D,
ScriptFormat0x0E,
ScriptFormat0x0F,
// Complexity errors
/// 0x10: The request contains too many sources.
RequestTooManySources,
/// 0x11: The script contains too many calls.
ScriptTooManyCalls,
/// Unallocated
Complexity0x12,
Complexity0x13,
Complexity0x14,
Complexity0x15,
Complexity0x16,
Complexity0x17,
Complexity0x18,
Complexity0x19,
Complexity0x1A,
Complexity0x1B,
Complexity0x1C,
Complexity0x1D,
Complexity0x1E,
Complexity0x1F,
// Operator errors
/// 0x20: The operator does not exist.
UnsupportedOperator,
/// Unallocated
Operator0x21,
Operator0x22,
Operator0x23,
Operator0x24,
Operator0x25,
Operator0x26,
Operator0x27,
Operator0x28,
Operator0x29,
Operator0x2A,
Operator0x2B,
Operator0x2C,
Operator0x2D,
Operator0x2E,
Operator0x2F,
// Retrieval-specific errors
/// 0x30: At least one of the sources could not be retrieved, but returned HTTP error.
HTTP,
/// 0x31: Retrieval of at least one of the sources timed out.
RetrievalTimeout,
/// Unallocated
Retrieval0x32,
Retrieval0x33,
Retrieval0x34,
Retrieval0x35,
Retrieval0x36,
Retrieval0x37,
Retrieval0x38,
Retrieval0x39,
Retrieval0x3A,
Retrieval0x3B,
Retrieval0x3C,
Retrieval0x3D,
Retrieval0x3E,
Retrieval0x3F,
// Math errors
/// 0x40: Math operator caused an underflow.
Underflow,
/// 0x41: Math operator caused an overflow.
Overflow,
/// 0x42: Tried to divide by zero.
DivisionByZero,
Size
}
/*
Result impl's
*/
/**
* @notice Decode raw CBOR bytes into a Result instance.
* @param _cborBytes Raw bytes representing a CBOR-encoded value.
* @return A `Result` instance.
*/
function resultFromCborBytes(bytes calldata _cborBytes) external pure returns(Result memory) {
CBOR.Value memory cborValue = CBOR.valueFromBytes(_cborBytes);
return resultFromCborValue(cborValue);
}
/**
* @notice Decode a CBOR value into a Result instance.
* @param _cborValue An instance of `CBOR.Value`.
* @return A `Result` instance.
*/
function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) {
// Witnet uses CBOR tag 39 to represent RADON error code identifiers.
// [CBOR tag 39] Identifiers for CBOR: https://github.com/lucas-clemente/cbor-specs/blob/master/id.md
bool success = _cborValue.tag != 39;
return Result(success, _cborValue);
}
/**
* @notice Tell if a Result is successful.
* @param _result An instance of Result.
* @return `true` if successful, `false` if errored.
*/
function isOk(Result memory _result) public pure returns(bool) {
return _result.success;
}
/**
* @notice Tell if a Result is errored.
* @param _result An instance of Result.
* @return `true` if errored, `false` if successful.
*/
function isError(Result memory _result) public pure returns(bool) {
return !_result.success;
}
/**
* @notice Decode a bytes value from a Result as a `bytes` value.
* @param _result An instance of Result.
* @return The `bytes` decoded from the Result.
*/
function asBytes(Result memory _result) public pure returns(bytes memory) {
require(_result.success, "Tried to read bytes value from errored Result");
return _result.cborValue.decodeBytes();
}
/**
* @notice Decode an error code from a Result as a member of `ErrorCodes`.
* @param _result An instance of `Result`.
* @return The `CBORValue.Error memory` decoded from the Result.
*/
function asErrorCode(Result memory _result) public pure returns(ErrorCodes) {
uint64[] memory error = asRawError(_result);
return supportedErrorOrElseUnknown(error[0]);
}
/**
* @notice Generate a suitable error message for a member of `ErrorCodes` and its corresponding arguments.
* @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function
* @param _result An instance of `Result`.
* @return A tuple containing the `CBORValue.Error memory` decoded from the `Result`, plus a loggable error message.
*/
function asErrorMessage(Result memory _result) public pure returns(ErrorCodes, string memory) {
uint64[] memory error = asRawError(_result);
ErrorCodes errorCode = supportedErrorOrElseUnknown(error[0]);
bytes memory errorMessage;
if (errorCode == ErrorCodes.SourceScriptNotCBOR) {
errorMessage = abi.encodePacked("Source script #", utoa(error[1]), " was not a valid CBOR value");
} else if (errorCode == ErrorCodes.SourceScriptNotArray) {
errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not an Array of calls");
} else if (errorCode == ErrorCodes.SourceScriptNotRADON) {
errorMessage = abi.encodePacked("The CBOR value in script #", utoa(error[1]), " was not a valid RADON script");
} else if (errorCode == ErrorCodes.RequestTooManySources) {
errorMessage = abi.encodePacked("The request contained too many sources (", utoa(error[1]), ")");
} else if (errorCode == ErrorCodes.ScriptTooManyCalls) {
errorMessage = abi.encodePacked(
"Script #",
utoa(error[2]),
" from the ",
stageName(error[1]),
" stage contained too many calls (",
utoa(error[3]),
")"
);
} else if (errorCode == ErrorCodes.UnsupportedOperator) {
errorMessage = abi.encodePacked(
"Operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage is not supported"
);
} else if (errorCode == ErrorCodes.HTTP) {
errorMessage = abi.encodePacked(
"Source #",
utoa(error[1]),
" could not be retrieved. Failed with HTTP error code: ",
utoa(error[2] / 100),
utoa(error[2] % 100 / 10),
utoa(error[2] % 10)
);
} else if (errorCode == ErrorCodes.RetrievalTimeout) {
errorMessage = abi.encodePacked(
"Source #",
utoa(error[1]),
" could not be retrieved because of a timeout."
);
} else if (errorCode == ErrorCodes.Underflow) {
errorMessage = abi.encodePacked(
"Underflow at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else if (errorCode == ErrorCodes.Overflow) {
errorMessage = abi.encodePacked(
"Overflow at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else if (errorCode == ErrorCodes.DivisionByZero) {
errorMessage = abi.encodePacked(
"Division by zero at operator code 0x",
utohex(error[4]),
" found at call #",
utoa(error[3]),
" in script #",
utoa(error[2]),
" from ",
stageName(error[1]),
" stage"
);
} else {
errorMessage = abi.encodePacked("Unknown error (0x", utohex(error[0]), ")");
}
return (errorCode, string(errorMessage));
}
/**
* @notice Decode a raw error from a `Result` as a `uint64[]`.
* @param _result An instance of `Result`.
* @return The `uint64[]` raw error as decoded from the `Result`.
*/
function asRawError(Result memory _result) public pure returns(uint64[] memory) {
require(!_result.success, "Tried to read error code from successful Result");
return _result.cborValue.decodeUint64Array();
}
/**
* @notice Decode a fixed16 (half-precision) numeric value from a Result as an `int32` value.
* @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values.
* by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`.
* use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
* @param _result An instance of Result.
* @return The `int128` decoded from the Result.
*/
function asFixed16(Result memory _result) public pure returns(int32) {
require(_result.success, "Tried to read `fixed16` value from errored Result");
return _result.cborValue.decodeFixed16();
}
/**
* @notice Decode an array of fixed16 values from a Result as an `int128[]` value.
* @param _result An instance of Result.
* @return The `int128[]` decoded from the Result.
*/
function asFixed16Array(Result memory _result) public pure returns(int128[] memory) {
require(_result.success, "Tried to read `fixed16[]` value from errored Result");
return _result.cborValue.decodeFixed16Array();
}
/**
* @notice Decode a integer numeric value from a Result as an `int128` value.
* @param _result An instance of Result.
* @return The `int128` decoded from the Result.
*/
function asInt128(Result memory _result) public pure returns(int128) {
require(_result.success, "Tried to read `int128` value from errored Result");
return _result.cborValue.decodeInt128();
}
/**
* @notice Decode an array of integer numeric values from a Result as an `int128[]` value.
* @param _result An instance of Result.
* @return The `int128[]` decoded from the Result.
*/
function asInt128Array(Result memory _result) public pure returns(int128[] memory) {
require(_result.success, "Tried to read `int128[]` value from errored Result");
return _result.cborValue.decodeInt128Array();
}
/**
* @notice Decode a string value from a Result as a `string` value.
* @param _result An instance of Result.
* @return The `string` decoded from the Result.
*/
function asString(Result memory _result) public pure returns(string memory) {
require(_result.success, "Tried to read `string` value from errored Result");
return _result.cborValue.decodeString();
}
/**
* @notice Decode an array of string values from a Result as a `string[]` value.
* @param _result An instance of Result.
* @return The `string[]` decoded from the Result.
*/
function asStringArray(Result memory _result) public pure returns(string[] memory) {
require(_result.success, "Tried to read `string[]` value from errored Result");
return _result.cborValue.decodeStringArray();
}
/**
* @notice Decode a natural numeric value from a Result as a `uint64` value.
* @param _result An instance of Result.
* @return The `uint64` decoded from the Result.
*/
function asUint64(Result memory _result) public pure returns(uint64) {
require(_result.success, "Tried to read `uint64` value from errored Result");
return _result.cborValue.decodeUint64();
}
/**
* @notice Decode an array of natural numeric values from a Result as a `uint64[]` value.
* @param _result An instance of Result.
* @return The `uint64[]` decoded from the Result.
*/
function asUint64Array(Result memory _result) public pure returns(uint64[] memory) {
require(_result.success, "Tried to read `uint64[]` value from errored Result");
return _result.cborValue.decodeUint64Array();
}
/**
* @notice Convert a stage index number into the name of the matching Witnet request stage.
* @param _stageIndex A `uint64` identifying the index of one of the Witnet request stages.
* @return The name of the matching stage.
*/
function stageName(uint64 _stageIndex) public pure returns(string memory) {
if (_stageIndex == 0) {
return "retrieval";
} else if (_stageIndex == 1) {
return "aggregation";
} else if (_stageIndex == 2) {
return "tally";
} else {
return "unknown";
}
}
/**
* @notice Get an `ErrorCodes` item from its `uint64` discriminant, or default to `ErrorCodes.Unknown` if it doesn't
* exist.
* @param _discriminant The numeric identifier of an error.
* @return A member of `ErrorCodes`.
*/
function supportedErrorOrElseUnknown(uint64 _discriminant) private pure returns(ErrorCodes) {
if (_discriminant < uint8(ErrorCodes.Size)) {
return ErrorCodes(_discriminant);
} else {
return ErrorCodes.Unknown;
}
}
/**
* @notice Convert a `uint64` into a 1, 2 or 3 characters long `string` representing its.
* three less significant decimal values.
* @param _u A `uint64` value.
* @return The `string` representing its decimal value.
*/
function utoa(uint64 _u) private pure returns(string memory) {
if (_u < 10) {
bytes memory b1 = new bytes(1);
b1[0] = byte(uint8(_u) + 48);
return string(b1);
} else if (_u < 100) {
bytes memory b2 = new bytes(2);
b2[0] = byte(uint8(_u / 10) + 48);
b2[1] = byte(uint8(_u % 10) + 48);
return string(b2);
} else {
bytes memory b3 = new bytes(3);
b3[0] = byte(uint8(_u / 100) + 48);
b3[1] = byte(uint8(_u % 100 / 10) + 48);
b3[2] = byte(uint8(_u % 10) + 48);
return string(b3);
}
}
/**
* @notice Convert a `uint64` into a 2 characters long `string` representing its two less significant hexadecimal values.
* @param _u A `uint64` value.
* @return The `string` representing its hexadecimal value.
*/
function utohex(uint64 _u) private pure returns(string memory) {
bytes memory b2 = new bytes(2);
uint8 d0 = uint8(_u / 16) + 48;
uint8 d1 = uint8(_u % 16) + 48;
if (d0 > 57)
d0 += 7;
if (d1 > 57)
d1 += 7;
b2[0] = byte(d0);
b2[1] = byte(d1);
return string(b2);
}
}
// File: witnet-ethereum-bridge/contracts/Request.sol
/**
* @title The serialized form of a Witnet data request
*/
contract Request {
bytes public bytecode;
uint256 public id;
/**
* @dev A `Request` is constructed around a `bytes memory` value containing a well-formed Witnet data request serialized
* using Protocol Buffers. However, we cannot verify its validity at this point. This implies that contracts using
* the WRB should not be considered trustless before a valid Proof-of-Inclusion has been posted for the requests.
* The hash of the request is computed in the constructor to guarantee consistency. Otherwise there could be a
* mismatch and a data request could be resolved with the result of another.
* @param _bytecode Witnet request in bytes.
*/
constructor(bytes memory _bytecode) public {
bytecode = _bytecode;
id = uint256(sha256(_bytecode));
}
}
// File: witnet-ethereum-bridge/contracts/UsingWitnet.sol
/**
* @title The UsingWitnet contract
* @notice Contract writers can inherit this contract in order to create requests for the
* Witnet network.
*/
contract UsingWitnet {
using Witnet for Witnet.Result;
WitnetRequestsBoardProxy internal wrb;
/**
* @notice Include an address to specify the WitnetRequestsBoard.
* @param _wrb WitnetRequestsBoard address.
*/
constructor(address _wrb) public {
wrb = WitnetRequestsBoardProxy(_wrb);
}
// Provides a convenient way for client contracts extending this to block the execution of the main logic of the
// contract until a particular request has been successfully accepted into Witnet
modifier witnetRequestAccepted(uint256 _id) {
require(witnetCheckRequestAccepted(_id), "Witnet request is not yet accepted into the Witnet network");
_;
}
// Ensures that user-specified rewards are equal to the total transaction value to prevent users from burning any excess value
modifier validRewards(uint256 _requestReward, uint256 _resultReward) {
require(_requestReward + _resultReward >= _requestReward, "The sum of rewards overflows");
require(msg.value == _requestReward + _resultReward, "Transaction value should equal the sum of rewards");
_;
}
/**
* @notice Send a new request to the Witnet network
* @dev Call to `post_dr` function in the WitnetRequestsBoard contract
* @param _request An instance of the `Request` contract
* @param _requestReward Reward specified for the user which posts the request into Witnet
* @param _resultReward Reward specified for the user which posts back the request result
* @return Sequencial identifier for the request included in the WitnetRequestsBoard
*/
function witnetPostRequest(Request _request, uint256 _requestReward, uint256 _resultReward)
internal
validRewards(_requestReward, _resultReward)
returns (uint256)
{
return wrb.postDataRequest.value(_requestReward + _resultReward)(_request.bytecode(), _resultReward);
}
/**
* @notice Check if a request has been accepted into Witnet.
* @dev Contracts depending on Witnet should not start their main business logic (e.g. receiving value from third.
* parties) before this method returns `true`.
* @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard.
* @return A boolean telling if the request has been already accepted or not. `false` do not mean rejection, though.
*/
function witnetCheckRequestAccepted(uint256 _id) internal view returns (bool) {
// Find the request in the
uint256 drHash = wrb.readDrHash(_id);
// If the hash of the data request transaction in Witnet is not the default, then it means that inclusion of the
// request has been proven to the WRB.
return drHash != 0;
}
/**
* @notice Upgrade the rewards for a Data Request previously included.
* @dev Call to `upgrade_dr` function in the WitnetRequestsBoard contract.
* @param _id The sequential identifier of a request that has been previously sent to the WitnetRequestsBoard.
* @param _requestReward Reward specified for the user which posts the request into Witnet
* @param _resultReward Reward specified for the user which post the Data Request result.
*/
function witnetUpgradeRequest(uint256 _id, uint256 _requestReward, uint256 _resultReward)
internal
validRewards(_requestReward, _resultReward)
{
wrb.upgradeDataRequest.value(msg.value)(_id, _resultReward);
}
/**
* @notice Read the result of a resolved request.
* @dev Call to `read_result` function in the WitnetRequestsBoard contract.
* @param _id The sequential identifier of a request that was posted to Witnet.
* @return The result of the request as an instance of `Result`.
*/
function witnetReadResult(uint256 _id) internal view returns (Witnet.Result memory) {
return Witnet.resultFromCborBytes(wrb.readResult(_id));
}
}
// File: adomedianizer/contracts/IERC2362.sol
/**
* @dev EIP2362 Interface for pull oracles
* https://github.com/tellor-io/EIP-2362
*/
interface IERC2362
{
/**
* @dev Exposed function pertaining to EIP standards
* @param _id bytes32 ID of the query
* @return int,uint,uint returns the value, timestamp, and status code of query
*/
function valueFor(bytes32 _id) external view returns(int256,uint256,uint256);
}
// File: witnet-price-feeds-examples/contracts/requests/BitcoinPrice.sol
// The bytecode of the BitcoinPrice request that will be sent to Witnet
contract BitcoinPriceRequest is Request {
constructor () Request(hex"0abb0108c3aafbf405123b122468747470733a2f2f7777772e6269747374616d702e6e65742f6170692f7469636b65722f1a13841877821864646c6173748218571903e8185b125c123168747470733a2f2f6170692e636f696e6465736b2e636f6d2f76312f6270692f63757272656e7470726963652e6a736f6e1a2786187782186663627069821866635553448218646a726174655f666c6f61748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/bitcoin_price_feed/BtcUsdPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the BitcoinPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract BtcUsdPriceFeed is UsingWitnet, IERC2362 {
// The public Bitcoin price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is `keccak256("Price-BTC/USD-3")`
bytes32 constant public BTCUSD3ID = bytes32(hex"637b7efb6b620736c247aaa282f3898914c0bef6c12faff0d3fe9d4bea783020");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new BitcoinPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != BTCUSD3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: witnet-price-feeds-examples/contracts/requests/EthPrice.sol
// The bytecode of the EthPrice request that will be sent to Witnet
contract EthPriceRequest is Request {
constructor () Request(hex"0a850208d7affbf4051245122e68747470733a2f2f7777772e6269747374616d702e6e65742f6170692f76322f7469636b65722f6574687573642f1a13841877821864646c6173748218571903e8185b1247122068747470733a2f2f6170692e636f696e6361702e696f2f76322f6173736574731a238618778218616464617461821818018218646870726963655573648218571903e8185b1253122668747470733a2f2f6170692e636f696e70617072696b612e636f6d2f76312f7469636b6572731a29871876821818038218666671756f746573821866635553448218646570726963658218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/eth_price_feed/EthUsdPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the ethPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract EthUsdPriceFeed is UsingWitnet, IERC2362 {
// The public eth price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is the ERC2362 identifier for a eth price feed, computed as `keccak256("Price-ETH/USD-3")`
bytes32 constant public ETHUSD3ID = bytes32(hex"dfaa6f747f0f012e8f2069d6ecacff25f5cdf0258702051747439949737fc0b5");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new EthPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != ETHUSD3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: witnet-price-feeds-examples/contracts/requests/GoldPrice.sol
// The bytecode of the GoldPrice request that will be sent to Witnet
contract GoldPriceRequest is Request {
constructor () Request(hex"0ab90308c3aafbf4051257123f68747470733a2f2f636f696e7965702e636f6d2f6170692f76312f3f66726f6d3d58415526746f3d455552266c616e673d657326666f726d61743d6a736f6e1a148418778218646570726963658218571903e8185b1253122b68747470733a2f2f646174612d6173672e676f6c6470726963652e6f72672f64625852617465732f4555521a24861877821861656974656d73821818008218646878617550726963658218571903e8185b1255123668747470733a2f2f7777772e6d7963757272656e63797472616e736665722e636f6d2f6170692f63757272656e742f5841552f4555521a1b851877821866646461746182186464726174658218571903e8185b129101125d68747470733a2f2f7777772e696e766572736f726f2e65732f6461746f732f3f706572696f643d3379656172267869676e6974655f636f64653d5841552663757272656e63793d455552267765696768745f756e69743d6f756e6365731a308518778218666a7461626c655f64617461821864736d6574616c5f70726963655f63757272656e748218571903e8185b1a0d0a0908051205fa3fc00000100322090a0508051201011003100a18042001280130013801400248055046") public { }
}
// File: witnet-price-feeds-examples/contracts/gold_price_feed/GoldEurPriceFeed.sol
// Import the UsingWitnet library that enables interacting with Witnet
// Import the ERC2362 interface
// Import the goldPrice request that you created before
// Your contract needs to inherit from UsingWitnet
contract GoldEurPriceFeed is UsingWitnet, IERC2362 {
// The public gold price point
uint64 public lastPrice;
// Stores the ID of the last Witnet request
uint256 public lastRequestId;
// Stores the timestamp of the last time the public price point was updated
uint256 public timestamp;
// Tells if an update has been requested but not yet completed
bool public pending;
// The Witnet request object, is set in the constructor
Request public request;
// Emits when the price is updated
event priceUpdated(uint64);
// Emits when found an error decoding request result
event resultError(string);
// This is the ERC2362 identifier for a gold price feed, computed as `keccak256("Price-XAU/EUR-3")`
bytes32 constant public XAUEUR3ID = bytes32(hex"68cba0705475e40c1ddbf7dc7c1ae4e7320ca094c4e118d1067c4dea5df28590");
// This constructor does a nifty trick to tell the `UsingWitnet` library where
// to find the Witnet contracts on whatever Ethereum network you use.
constructor (address _wrb) UsingWitnet(_wrb) public {
// Instantiate the Witnet request
request = new GoldPriceRequest();
}
/**
* @notice Sends `request` to the WitnetRequestsBoard.
* @dev This method will only succeed if `pending` is 0.
**/
function requestUpdate() public payable {
require(!pending, "An update is already pending. Complete it first before requesting another update.");
// Amount to pay to the bridge node relaying this request from Ethereum to Witnet
uint256 _witnetRequestReward = 100 szabo;
// Amount of wei to pay to the bridge node relaying the result from Witnet to Ethereum
uint256 _witnetResultReward = 100 szabo;
// Send the request to Witnet and store the ID for later retrieval of the result
// The `witnetPostRequest` method comes with `UsingWitnet`
lastRequestId = witnetPostRequest(request, _witnetRequestReward, _witnetResultReward);
// Signal that there is already a pending request
pending = true;
}
/**
* @notice Reads the result, if ready, from the WitnetRequestsBoard.
* @dev The `witnetRequestAccepted` modifier comes with `UsingWitnet` and allows to
* protect your methods from being called before the request has been successfully
* relayed into Witnet.
**/
function completeUpdate() public witnetRequestAccepted(lastRequestId) {
require(pending, "There is no pending update.");
// Read the result of the Witnet request
// The `witnetReadResult` method comes with `UsingWitnet`
Witnet.Result memory result = witnetReadResult(lastRequestId);
// If the Witnet request succeeded, decode the result and update the price point
// If it failed, revert the transaction with a pretty-printed error message
if (result.isOk()) {
lastPrice = result.asUint64();
timestamp = block.timestamp;
emit priceUpdated(lastPrice);
} else {
string memory errorMessage;
// Try to read the value as an error message, catch error bytes if read fails
try result.asErrorMessage() returns (Witnet.ErrorCodes errorCode, string memory e) {
errorMessage = e;
}
catch (bytes memory errorBytes){
errorMessage = string(errorBytes);
}
emit resultError(errorMessage);
}
// In any case, set `pending` to false so a new update can be requested
pending = false;
}
/**
* @notice Exposes the public data point in an ERC2362 compliant way.
* @dev Returns error `400` if queried for an unknown data point, and `404` if `completeUpdate` has never been called
* successfully before.
**/
function valueFor(bytes32 _id) external view override returns(int256, uint256, uint256) {
// Unsupported data point ID
if(_id != XAUEUR3ID) return(0, 0, 400);
// No value is yet available for the queried data point ID
if (timestamp == 0) return(0, 0, 404);
int256 value = int256(lastPrice);
return(value, timestamp, 200);
}
}
// File: contracts/Deployer.sol
// Import witnet-ethereum-block-relay-contracts
// Import the UsingWitnet library that enables interacting with Witnet
// Import price feeds
contract Deployer {
}
// File: contracts/Migrations.sol
contract Migrations {
address public owner;
uint public lastCompletedMigration;
constructor() public {
owner = msg.sender;
}
modifier restricted() {
if (msg.sender == owner)
_;
}
function setCompleted(uint _completed) public restricted {
lastCompletedMigration = _completed;
}
function upgrade(address _newAddress) public restricted {
Migrations upgraded = Migrations(_newAddress);
upgraded.setCompleted(lastCompletedMigration);
}
}
| * @notice Decode a CBOR value into a Result instance. @param _cborValue An instance of `CBOR.Value`. @return A `Result` instance./ Witnet uses CBOR tag 39 to represent RADON error code identifiers. [CBOR tag 39] Identifiers for CBOR: https:github.com/lucas-clemente/cbor-specs/blob/master/id.md | function resultFromCborValue(CBOR.Value memory _cborValue) public pure returns(Result memory) {
bool success = _cborValue.tag != 39;
return Result(success, _cborValue);
}
| 901,266 | [
1,
6615,
279,
21262,
916,
460,
1368,
279,
3438,
791,
18,
225,
389,
7358,
280,
620,
1922,
791,
434,
1375,
8876,
916,
18,
620,
8338,
327,
432,
1375,
1253,
68,
791,
18,
19,
678,
305,
2758,
4692,
21262,
916,
1047,
16977,
358,
2406,
534,
1880,
673,
555,
981,
9863,
18,
306,
8876,
916,
1047,
16977,
65,
13128,
3383,
364,
21262,
916,
30,
2333,
30,
6662,
18,
832,
19,
80,
5286,
345,
17,
71,
806,
73,
19,
7358,
280,
17,
15115,
19,
10721,
19,
7525,
19,
350,
18,
1264,
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
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
]
| [
1,
225,
445,
563,
1265,
15237,
280,
620,
12,
8876,
916,
18,
620,
3778,
389,
7358,
280,
620,
13,
1071,
16618,
1135,
12,
1253,
3778,
13,
288,
203,
565,
1426,
2216,
273,
389,
7358,
280,
620,
18,
2692,
480,
16977,
31,
203,
565,
327,
3438,
12,
4768,
16,
389,
7358,
280,
620,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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
pragma solidity >=0.8.0;
// ====================================================================
// | ______ _______ |
// | / _____________ __ __ / ____(_____ ____ _____ ________ |
// | / /_ / ___/ __ `| |/_/ / /_ / / __ \/ __ `/ __ \/ ___/ _ \ |
// | / __/ / / / /_/ _> < / __/ / / / / / /_/ / / / / /__/ __/ |
// | /_/ /_/ \__,_/_/|_| /_/ /_/_/ /_/\__,_/_/ /_/\___/\___/ |
// | |
// ====================================================================
// ============================ MSIGHelper ============================
// ====================================================================
// Accepts tokens from the AMO Minter and then lends them to an MSIG
// Frax Finance: https://github.com/FraxFinance
// Primary Author(s)
// Travis Moore: https://github.com/FortisFortuna
// Reviewer(s) / Contributor(s)
// Sam Kazemian: https://github.com/samkazemian
// Jason Huan: https://github.com/jasonhuan
import "../Math/Math.sol";
import "../Frax/IFrax.sol";
import "../FXS/IFxs.sol";
import "../Frax/IFraxAMOMinter.sol";
import "../ERC20/ERC20.sol";
import '../Uniswap/TransferHelper.sol';
import "../Staking/Owned.sol";
contract MSIGHelper is Owned {
/* ========== STATE VARIABLES ========== */
// Instances and addresses
IFrax public FRAX = IFrax(0x853d955aCEf822Db058eb8505911ED77F175b99e);
IFxs public FXS = IFxs(0x3432B6A60D23Ca0dFCa7761B7ab56459D9C964D0);
ERC20 public collateral_token;
IFraxAMOMinter public amo_minter;
// Price constants
uint256 private constant PRICE_PRECISION = 1e6;
// AMO Minter related
address public amo_minter_address;
// Collateral related
address public collateral_address;
uint256 public col_idx;
// Admin addresses
address public timelock_address;
// Bridge related
address public msig_address;
// Balance tracking
uint256 public frax_lent;
uint256 public fxs_lent;
uint256 public collat_lent;
// Collateral balance related
uint256 public missing_decimals;
/* ========== MODIFIERS ========== */
modifier onlyByOwnGov() {
require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor (
address _owner,
address _amo_minter_address,
address _msig_address
) Owned(_owner) {
// AMO Minter related
amo_minter_address = _amo_minter_address;
amo_minter = IFraxAMOMinter(_amo_minter_address);
timelock_address = amo_minter.timelock_address();
// MSIG related
msig_address = _msig_address;
// Collateral related
collateral_address = amo_minter.collateral_address();
col_idx = amo_minter.col_idx();
collateral_token = ERC20(collateral_address);
missing_decimals = amo_minter.missing_decimals();
}
/* ========== VIEWS ========== */
function getTokenType(address token_address) public view returns (uint256) {
// 0 = FRAX, 1 = FXS, 2 = Collateral
if (token_address == address(FRAX)) return 0;
else if (token_address == address(FXS)) return 1;
else if (token_address == address(collateral_token)) return 2;
// Revert on invalid tokens
revert("getTokenType: Invalid token");
}
function showTokenBalances() public view returns (uint256[3] memory tkn_bals) {
tkn_bals[0] = FRAX.balanceOf(address(this)); // FRAX
tkn_bals[1] = FXS.balanceOf(address(this)); // FXS
tkn_bals[2] = collateral_token.balanceOf(address(this)); // Collateral
}
function showAllocations() public view returns (uint256[10] memory allocations) {
// All numbers given are in FRAX unless otherwise stated
// Get some token balances
uint256[3] memory tkn_bals = showTokenBalances();
// FRAX
allocations[0] = tkn_bals[0]; // Free FRAX
allocations[1] = frax_lent; // Lent FRAX
allocations[2] = allocations[0] + allocations[1]; // Total FRAX
// FXS
allocations[3] = tkn_bals[1]; // Free FXS
allocations[4] = fxs_lent; // Lent FXS
allocations[5] = allocations[3] + allocations[4]; // Total FXS
// Collateral
allocations[6] = tkn_bals[2] * (10 ** missing_decimals); // Free Collateral, in E18
allocations[7] = collat_lent * (10 ** missing_decimals); // Lent Collateral, in E18
allocations[8] = allocations[6] + allocations[7]; // Total Collateral, in E18
// Total USD value, in E18
// Ignores FXS
allocations[9] = allocations[2] + allocations[8];
}
// Needed for the Frax contract to function
function collatDollarBalance() public view returns (uint256) {
(, uint256 col_bal) = dollarBalances();
return col_bal;
}
function dollarBalances() public view returns (uint256 frax_val_e18, uint256 collat_val_e18) {
// NOTE: The token tracker will track the actual FRAX, FXS, and Collat on the msig
// Were it to be included here too, it would be a double count
// Get the allocations
uint256[10] memory allocations = showAllocations();
// FRAX portion is Frax * CR
uint256 frax_portion_with_cr = (allocations[0] * FRAX.global_collateral_ratio()) / PRICE_PRECISION;
// Collateral portion
uint256 collat_portion = allocations[6];
// Total value, not including CR, ignoring FXS
frax_val_e18 = allocations[0] + allocations[6];
// Collat value, accounting for CR on the FRAX portion
collat_val_e18 = collat_portion + frax_portion_with_cr;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function lend(address token_address, uint256 token_amount) external onlyByOwnGov {
// Get the token type
uint256 token_type = getTokenType(token_address);
// Can be overridden
if (token_type == 0){
TransferHelper.safeTransfer(address(FRAX), msig_address, token_amount);
frax_lent += token_amount;
}
else if (token_type == 1) {
TransferHelper.safeTransfer(address(FXS), msig_address, token_amount);
fxs_lent += token_amount;
}
else {
TransferHelper.safeTransfer(collateral_address, msig_address, token_amount);
collat_lent += token_amount;
}
}
/* ========== Burns and givebacks ========== */
// Burn unneeded or excess FRAX. Goes through the minter
function burnFRAX(uint256 frax_amount) public onlyByOwnGov {
FRAX.approve(amo_minter_address, frax_amount);
amo_minter.burnFraxFromAMO(frax_amount);
// Update the balance after the transfer goes through
if (frax_amount >= frax_lent) frax_lent = 0;
else {
frax_lent -= frax_amount;
}
}
// Burn unneeded or excess FXS. Goes through the minter
function burnFXS(uint256 fxs_amount) public onlyByOwnGov {
FXS.approve(amo_minter_address, fxs_amount);
amo_minter.burnFxsFromAMO(fxs_amount);
// Update the balance after the transfer goes through
if (fxs_amount >= fxs_lent) fxs_lent = 0;
else {
fxs_lent -= fxs_amount;
}
}
// Give collat profits back. Goes through the minter
function giveCollatBack(uint256 collat_amount) external onlyByOwnGov {
collateral_token.approve(amo_minter_address, collat_amount);
amo_minter.receiveCollatFromAMO(collat_amount);
// Update the balance after the transfer goes through
if (collat_amount >= collat_lent) collat_lent = 0;
else {
collat_lent -= collat_amount;
}
}
/* ========== RESTRICTED FUNCTIONS - Owner or timelock only ========== */
function setTimelock(address _new_timelock) external onlyByOwnGov {
timelock_address = _new_timelock;
}
function setMsigAddress(address _msig_address) external onlyByOwnGov {
require(_msig_address != address(0), "Invalid msig address");
msig_address = _msig_address;
}
function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyByOwnGov {
// Only the owner address can ever receive the recovery withdrawal
TransferHelper.safeTransfer(tokenAddress, owner, tokenAmount);
emit RecoveredERC20(tokenAddress, tokenAmount);
}
// Generic proxy
function execute(
address _to,
uint256 _value,
bytes calldata _data
) external onlyByOwnGov returns (bool, bytes memory) {
(bool success, bytes memory result) = _to.call{value:_value}(_data);
return (success, result);
}
/* ========== EVENTS ========== */
event RecoveredERC20(address token, uint256 amount);
event BridgeInfoChanged(address frax_bridge_address, address fxs_bridge_address, address collateral_bridge_address, address destination_address_override, string non_evm_destination_address);
} | ========== MODIFIERS ========== */ | modifier onlyByOwnGov() {
require(msg.sender == owner || msg.sender == timelock_address, "Not owner or timelock");
_;
}
constructor (
address _owner,
address _amo_minter_address,
address _msig_address
| 12,560,025 | [
1,
1432,
631,
8663,
10591,
55,
422,
1432,
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,
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,
9606,
1338,
858,
5460,
43,
1527,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
3410,
747,
1234,
18,
15330,
422,
1658,
292,
975,
67,
2867,
16,
315,
1248,
3410,
578,
1658,
292,
975,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
261,
203,
3639,
1758,
389,
8443,
16,
203,
3639,
1758,
389,
301,
83,
67,
1154,
387,
67,
2867,
16,
203,
3639,
1758,
389,
959,
360,
67,
2867,
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
]
|
./full_match/5/0x848A8f863Dbd6723AC4a62Fb9a8d8Ff669aCe868/sources/contracts/MafiaNuts.sol | total supplyallowlist mint supplytrading competition supplymerkle root for allowlist addressestoken metadata variablesallowlist mint begins on March 14 2023 14:00:00 UTCPublic mint begins on March 15 2023 14:00:00 UTCmapping for allowlist claim statusmapping for public mint limitmapping for staking statusmapping for tokenId levelfunction to upgrade level of a token function upgradeToken(uint256 levelNumber) public{ require(isStaked[msg.sender], "You must stake your token to upgrade it."); require(level[tokenOfOwnerByIndex(msg.sender, 0)] < 10, "You have already upgraded your token to the max level."); level[tokenOfOwnerByIndex(msg.sender, 0)]++; }stake eventunstake eventPublic mint function | 2 NFTs per wallet | contract MafiaNuts is Ownable, ERC721A, ReentrancyGuard {
using Strings for uint256;
uint256 public MAX_SUPPLY = 2222;
uint256 public AL_SUPPLY_REMAINING = 600;
uint256 public TRADING_COMPETITION_SUPPLY = 69;
bytes32 public merkleRoot;
string private baseTokenURI;
string private defaultURI;
bool public isRevealed;
uint256 public AL_START_TIME = 1657952000;
uint256 public PUBLIC_START_TIME = 1658038400;
mapping (address => bool) internal hasClaimed;
mapping (address => uint256) public walletMints;
mapping (uint256 => bool) public isStaked;
mapping (uint256 => uint256) public level;
event Staked(address indexed staker, uint256 tokenId);
event Unstaked(address indexed staker, uint256 tokenId);
constructor() ERC721A("Mafia Nuts", "NUTS") {}
function mint(uint256 _amount) external {
require(
_amount > 0 && _amount <= 2,
"You can only mint 2 NFTs."
);
require(
walletMints[msg.sender] + _amount <= 2,
"You have already minted the maximum amount of NFTs."
);
require(
block.timestamp >= PUBLIC_START_TIME,
"Public minting has not begun yet."
);
require(
totalSupply() + _amount <= MAX_SUPPLY - AL_SUPPLY_REMAINING - TRADING_COMPETITION_SUPPLY,
"Mint would exceed max supply."
);
require(
tx.origin == msg.sender,
"No contracts are allowed to mint."
);
_safeMint(msg.sender, _amount);
walletMints[msg.sender] += _amount;
}
function ALMint(bytes32[] calldata merkleProof) external {
require (
block.timestamp >= AL_START_TIME,
"Allowlist minting has not begun yet."
);
require (
!hasClaimed[msg.sender],
"You have already claimed your allowlist NFT."
);
require (
totalSupply() <= MAX_SUPPLY,
"Mint would exceed max supply."
);
require (
tx.origin == msg.sender,
"No contracts are allowed to mint."
);
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(merkleProof, merkleRoot, leaf), "Invalid proof.");
hasClaimed[msg.sender] = true;
unchecked {
AL_SUPPLY_REMAINING--;
}
_safeMint(msg.sender, 1);
}
function ALMint(bytes32[] calldata merkleProof) external {
require (
block.timestamp >= AL_START_TIME,
"Allowlist minting has not begun yet."
);
require (
!hasClaimed[msg.sender],
"You have already claimed your allowlist NFT."
);
require (
totalSupply() <= MAX_SUPPLY,
"Mint would exceed max supply."
);
require (
tx.origin == msg.sender,
"No contracts are allowed to mint."
);
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(merkleProof, merkleRoot, leaf), "Invalid proof.");
hasClaimed[msg.sender] = true;
unchecked {
AL_SUPPLY_REMAINING--;
}
_safeMint(msg.sender, 1);
}
function teamMint() external onlyOwner {
require(totalSupply() == 0, "The team has already minted.");
_safeMint(msg.sender, 50);
}
function mintNutTo(address _winner) external onlyOwner {
require(totalSupply() < MAX_SUPPLY, "Mint would exceed max supply");
unchecked {
TRADING_COMPETITION_SUPPLY--;
}
_safeMint(_winner, 1);
}
function mintNutTo(address _winner) external onlyOwner {
require(totalSupply() < MAX_SUPPLY, "Mint would exceed max supply");
unchecked {
TRADING_COMPETITION_SUPPLY--;
}
_safeMint(_winner, 1);
}
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
merkleRoot = _merkleRoot;
}
function canClaimAL(address _address, bytes32[] calldata _merkleProof)
public
view
returns (bool)
{
return !hasClaimed[_address] && MerkleProof.verify(
_merkleProof,
merkleRoot,
keccak256(abi.encodePacked(_address))
);
}
function _baseURI() internal view override returns (string memory) {
return baseTokenURI;
}
function reveal(string calldata _baseURI) external onlyOwner{
isRevealed = true;
baseTokenURI = _baseURI;
}
function setDefaultURI(string calldata _defaultURI) external onlyOwner {
defaultURI = _defaultURI;
}
function tokenURI(uint256 _tokenId) public view override returns (string memory){
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
return isRevealed ? string(abi.encodePacked(
baseTokenURI,
_tokenId.toString()
)) : defaultURI;
}
function stake(uint256 tokenId) external {
require(
balanceOf(msg.sender) > 0,
"You do not own any NFTs."
);
isStaked[tokenId] = !isStaked[tokenId];
}
function _beforeTokenTransfers(
address,
address,
uint256 startTokenId,
uint256 quantity
) internal view override {
uint256 tokenId = startTokenId;
for (uint256 end = tokenId + quantity; tokenId < end; ++tokenId){
require(
!isStaked[tokenId],
"You can't transfer, it is staked."
);
}
}
function _beforeTokenTransfers(
address,
address,
uint256 startTokenId,
uint256 quantity
) internal view override {
uint256 tokenId = startTokenId;
for (uint256 end = tokenId + quantity; tokenId < end; ++tokenId){
require(
!isStaked[tokenId],
"You can't transfer, it is staked."
);
}
}
}
| 1,906,983 | [
1,
4963,
14467,
5965,
1098,
312,
474,
14467,
313,
14968,
25163,
608,
14467,
6592,
15609,
1365,
364,
1699,
1098,
1758,
395,
969,
1982,
3152,
5965,
1098,
312,
474,
17874,
603,
490,
991,
5045,
26599,
23,
5045,
30,
713,
30,
713,
4732,
4258,
447,
312,
474,
17874,
603,
490,
991,
4711,
26599,
23,
5045,
30,
713,
30,
713,
9951,
6770,
364,
1699,
1098,
7516,
1267,
6770,
364,
1071,
312,
474,
1800,
6770,
364,
384,
6159,
1267,
6770,
364,
1147,
548,
1801,
915,
358,
8400,
1801,
434,
279,
1147,
445,
8400,
1345,
12,
11890,
5034,
1801,
1854,
13,
1071,
95,
377,
2583,
12,
291,
510,
9477,
63,
3576,
18,
15330,
6487,
315,
6225,
1297,
384,
911,
3433,
1147,
358,
8400,
518,
1199,
1769,
377,
2583,
12,
2815,
63,
2316,
951,
5541,
21268,
12,
3576,
18,
15330,
16,
374,
25887,
411,
1728,
16,
315,
6225,
1240,
1818,
31049,
3433,
1147,
358,
326,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
16351,
490,
1727,
1155,
50,
12940,
353,
14223,
6914,
16,
4232,
39,
27,
5340,
37,
16,
868,
8230,
12514,
16709,
288,
203,
377,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
377,
203,
565,
2254,
5034,
1071,
4552,
67,
13272,
23893,
273,
576,
28855,
31,
203,
203,
565,
2254,
5034,
1071,
7981,
67,
13272,
23893,
67,
862,
19803,
1360,
273,
14707,
31,
203,
203,
565,
2254,
5034,
1071,
4235,
30118,
67,
4208,
1423,
56,
7022,
67,
13272,
23893,
273,
20963,
31,
203,
203,
565,
1731,
1578,
1071,
30235,
2375,
31,
203,
203,
565,
533,
3238,
1026,
1345,
3098,
31,
203,
565,
533,
3238,
805,
3098,
31,
203,
565,
1426,
1071,
28627,
537,
18931,
31,
203,
203,
565,
2254,
5034,
1071,
7981,
67,
7570,
67,
4684,
273,
2872,
25,
7235,
9401,
3784,
31,
203,
203,
565,
2254,
5034,
1071,
17187,
67,
7570,
67,
4684,
273,
2872,
25,
3672,
17295,
713,
31,
203,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
2713,
711,
9762,
329,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
1071,
9230,
49,
28142,
31,
203,
203,
565,
2874,
261,
11890,
5034,
516,
1426,
13,
1071,
353,
510,
9477,
31,
203,
203,
565,
2874,
261,
11890,
5034,
516,
2254,
5034,
13,
1071,
1801,
31,
203,
203,
203,
203,
565,
871,
934,
9477,
12,
2867,
8808,
384,
6388,
16,
2254,
5034,
1147,
548,
1769,
203,
203,
565,
871,
1351,
334,
9477,
12,
2867,
8808,
384,
6388,
16,
2254,
5034,
1147,
548,
1769,
203,
203,
203,
565,
3885,
1435,
4232,
2
]
|
pragma solidity ^0.4.24;
/**
@dev Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
constructor() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0, "Amount must be greater than zero.");
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0), "Must be valid, not null address.");
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this), "Address must not be the contract address.");
_;
}
}
| verifies that the address is different than this contract address | modifier notThis(address _address) {
require(_address != address(this), "Address must not be the contract address.");
_;
}
| 6,489,808 | [
1,
502,
5032,
716,
326,
1758,
353,
3775,
2353,
333,
6835,
1758,
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,
9606,
486,
2503,
12,
2867,
389,
2867,
13,
288,
203,
3639,
2583,
24899,
2867,
480,
1758,
12,
2211,
3631,
315,
1887,
1297,
486,
506,
326,
6835,
1758,
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
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
contract WMC is ERC20Burnable, Ownable {
/*
/$$ /$$ /$$ /$$ /$$$$$$
| $$ /$ | $$| $$$ /$$$ /$$__ $$
| $$ /$$$| $$| $$$$ /$$$$| $$ \__/
| $$/$$ $$ $$| $$ $$/$$ $$| $$
| $$$$_ $$$$| $$ $$$| $$| $$
| $$$/ \ $$$| $$\ $ | $$| $$ $$
| $$/ \ $$| $$ \/ | $$| $$$$$$/
|__/ \__/|__/ |__/ \______/
Minted by the Presidents
*/
using SafeMath for uint256;
uint256 public MAX_WALLET_STAKED = 100;
uint256 public EMISSIONS_RATE = 11574070000000;
uint256 public CLAIM_END_TIME = 1648763999;
address nullAddress = 0x0000000000000000000000000000000000000000;
address public washieAddress; // tokenid's 1 - 10,000
address public abeAddress; // tokenid's 10001 - 15000
address public hamiltonAddress; // tokenid's 15001 - 17500
address public jacksonAddress; // tokenid's 17501 - 19000
address public grantAddress; // tokenid's 19001 - 19750
address public bennyAddress; // tokenid's 19751 - 20000
//Mapping of president to timestamp
mapping(uint256 => uint256) internal tokenIdToTimeStamp;
//Mapping of president to staker
mapping(uint256 => address) internal tokenIdToStaker;
//Mapping of staker to president
mapping(address => uint256[]) internal stakerToTokenIds;
constructor() ERC20("We Mint Cash", "WMC") {
}
function setWashieAddress(address _washieAddress) public onlyOwner {
washieAddress = _washieAddress;
return;
}
function setAbeAddress(address _abeAddress) public onlyOwner {
abeAddress = _abeAddress;
return;
}
function setHamiltonAddress(address _hamiltonAddress) public onlyOwner {
hamiltonAddress = _hamiltonAddress;
return;
}
function setJacksonAddress(address _jacksonAddress) public onlyOwner {
jacksonAddress = _jacksonAddress;
return;
}
function setGrantAddress(address _grantAddress) public onlyOwner {
grantAddress = _grantAddress;
return;
}
function setBennyAddress(address _bennyAddress) public onlyOwner {
bennyAddress = _bennyAddress;
return;
}
function getTokensStaked(address staker)
public
view
returns (uint256[] memory)
{
return stakerToTokenIds[staker];
}
function remove(address staker, uint256 index) internal {
if (index >= stakerToTokenIds[staker].length) return;
for (uint256 i = index; i < stakerToTokenIds[staker].length - 1; i++) {
stakerToTokenIds[staker][i] = stakerToTokenIds[staker][i + 1];
}
stakerToTokenIds[staker].pop();
}
function removeTokenIdFromStaker(address staker, uint256 tokenId) internal {
for (uint256 i = 0; i < stakerToTokenIds[staker].length; i++) {
if (stakerToTokenIds[staker][i] == tokenId) {
//This is the tokenId to remove;
remove(staker, i);
}
}
}
function stakeByIds(uint256[] memory tokenIds) public {
require(
stakerToTokenIds[msg.sender].length + tokenIds.length <=
MAX_WALLET_STAKED,
"Must have less than 31 presidents staked!"
);
address prez;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
prez = washieAddress ;
} else if (tokenIds[i] > 10000 && tokenIds[i] <= 15000) {
prez = abeAddress;
} else if (tokenIds[i] > 15000 && tokenIds[i] <= 17500) {
prez = hamiltonAddress;
} else if (tokenIds[i] > 17500 && tokenIds[i] <= 18000) {
prez = jacksonAddress;
} else if (tokenIds[i] > 18000 && tokenIds[i] <= 19000) {
prez = grantAddress;
} else if (tokenIds[i] > 19000 && tokenIds[i] <= 20000) {
prez = bennyAddress;
}
require(
IERC721(prez).ownerOf(tokenIds[i]) == msg.sender
&&
tokenIdToStaker[tokenIds[i]] == nullAddress,
"Token must be stakable by you!"
);
IERC721(prez).transferFrom(
msg.sender,
address(this),
tokenIds[i]
);
stakerToTokenIds[msg.sender].push(tokenIds[i]);
tokenIdToTimeStamp[tokenIds[i]] = block.timestamp;
tokenIdToStaker[tokenIds[i]] = msg.sender;
}
}
function unstakeAll() public {
require(
stakerToTokenIds[msg.sender].length > 0,
"Must have at least one token staked!"
);
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
address prez;
for (uint256 i = stakerToTokenIds[msg.sender].length; i > 0; i--) {
uint256 tokenId = stakerToTokenIds[msg.sender][i - 1];
if (tokenId <= 10000) {
prez = washieAddress;
presidentEmissions = EMISSIONS_RATE;
} else if (tokenId > 10000 && tokenId <= 15000) {
prez = abeAddress;
presidentEmissions = EMISSIONS_RATE * 5;
} else if (tokenId > 15000 && tokenId <= 17500) {
prez = hamiltonAddress;
presidentEmissions = EMISSIONS_RATE * 10;
} else if (tokenId > 17500 && tokenId <= 18000) {
prez = jacksonAddress;
presidentEmissions = EMISSIONS_RATE * 20;
} else if (tokenId > 18000 && tokenId <= 19000) {
prez = grantAddress;
presidentEmissions = EMISSIONS_RATE * 50;
} else if (tokenId > 19000 && tokenId <= 20000) {
prez = bennyAddress;
presidentEmissions = EMISSIONS_RATE * 100;
}
IERC721(prez).transferFrom(
address(this),
msg.sender,
tokenId
);
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenId]) *
presidentEmissions);
removeTokenIdFromStaker(msg.sender, tokenId);
tokenIdToStaker[tokenId] = nullAddress;
_mint(msg.sender, totalRewards);
}
}
function unstakeByIds(uint256[] memory tokenIds) public {
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
address prez;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
prez = washieAddress;
presidentEmissions = EMISSIONS_RATE;
} else if (tokenIds[i] > 10000 && tokenIds[i] <= 15000) {
prez = abeAddress;
presidentEmissions = EMISSIONS_RATE * 5;
} else if (tokenIds[i] > 15000 && tokenIds[i] <= 17500) {
prez = hamiltonAddress;
presidentEmissions = EMISSIONS_RATE * 10;
} else if (tokenIds[i] > 17500 && tokenIds[i] <= 18000) {
prez = jacksonAddress;
presidentEmissions = EMISSIONS_RATE * 20;
} else if (tokenIds[i] > 18000 && tokenIds[i] <= 19000) {
prez = grantAddress;
presidentEmissions = EMISSIONS_RATE * 50;
} else if (tokenIds[i] > 19000 && tokenIds[i] <= 20000) {
prez = bennyAddress;
presidentEmissions = EMISSIONS_RATE * 100;
}
require(
tokenIdToStaker[tokenIds[i]] == msg.sender,
"Message Sender was not original staker!"
);
IERC721(prez).transferFrom(
address(this),
msg.sender,
tokenIds[i]
);
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
removeTokenIdFromStaker(msg.sender, tokenIds[i]);
tokenIdToStaker[tokenIds[i]] = nullAddress;
_mint(msg.sender, totalRewards);
}
}
function claimByTokenId(uint256 tokenId) public {
require(
tokenIdToStaker[tokenId] == msg.sender,
"Token is not claimable by you!"
);
require(block.timestamp < CLAIM_END_TIME, "Claim period is over!");
uint256 presidentEmissions = 0;
if (tokenId <= 10000) {
presidentEmissions = EMISSIONS_RATE;
} else if (tokenId > 10000 && tokenId <= 15000) {
presidentEmissions = EMISSIONS_RATE * 5;
} else if (tokenId > 15000 && tokenId <= 17500) {
presidentEmissions = EMISSIONS_RATE * 10;
} else if (tokenId > 17500 && tokenId <= 18000) {
presidentEmissions = EMISSIONS_RATE * 20;
} else if (tokenId > 18000 && tokenId <= 19000) {
presidentEmissions = EMISSIONS_RATE * 50;
} else if (tokenId > 19000 && tokenId <= 20000) {
presidentEmissions = EMISSIONS_RATE * 100;
}
_mint(
msg.sender,
((block.timestamp - tokenIdToTimeStamp[tokenId]) * presidentEmissions)
);
tokenIdToTimeStamp[tokenId] = block.timestamp;
}
function claimAll() public {
require(block.timestamp < CLAIM_END_TIME, "Claim period is over!");
uint256[] memory tokenIds = stakerToTokenIds[msg.sender];
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
tokenIdToStaker[tokenIds[i]] == msg.sender,
"Token is not claimable by you!"
);
if (tokenIds[i] <= 10000) {
presidentEmissions = EMISSIONS_RATE;
} else if (tokenIds[i] > 10000 && tokenIds[i] <= 15000) {
presidentEmissions = EMISSIONS_RATE * 5;
} else if (tokenIds[i] > 15000 && tokenIds[i] <= 17500) {
presidentEmissions = EMISSIONS_RATE * 10;
} else if (tokenIds[i] > 17500 && tokenIds[i] <= 18000) {
presidentEmissions = EMISSIONS_RATE * 20;
} else if (tokenIds[i] > 18000 && tokenIds[i] <= 19000) {
presidentEmissions = EMISSIONS_RATE * 50;
} else if (tokenIds[i] > 19000 && tokenIds[i] <= 20000) {
presidentEmissions = EMISSIONS_RATE * 100;
}
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
tokenIdToTimeStamp[tokenIds[i]] = block.timestamp;
}
_mint(msg.sender, totalRewards);
}
function getAllRewards(address staker) public view returns (uint256) {
uint256[] memory tokenIds = stakerToTokenIds[staker];
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
presidentEmissions = EMISSIONS_RATE;
} else if (tokenIds[i] > 10000 && tokenIds[i] <= 15000) {
presidentEmissions = EMISSIONS_RATE * 5;
} else if (tokenIds[i] > 15000 && tokenIds[i] <= 17500) {
presidentEmissions = EMISSIONS_RATE * 10;
} else if (tokenIds[i] > 17500 && tokenIds[i] <= 18000) {
presidentEmissions = EMISSIONS_RATE * 20;
} else if (tokenIds[i] > 18000 && tokenIds[i] <= 19000) {
presidentEmissions = EMISSIONS_RATE * 50;
} else if (tokenIds[i] > 19000 && tokenIds[i] <= 20000) {
presidentEmissions = EMISSIONS_RATE * 100;
}
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
}
return totalRewards;
}
function getRewardsByTokenId(uint256 tokenId)
public
view
returns (uint256)
{
require(
tokenIdToStaker[tokenId] != nullAddress,
"Token is not staked!"
);
uint256 presidentRewards = 0;
if (tokenId <= 10000) {
presidentRewards = EMISSIONS_RATE;
} else if (tokenId > 10000 && tokenId <= 15000) {
presidentRewards = EMISSIONS_RATE * 5;
} else if (tokenId > 15000 && tokenId <= 17500) {
presidentRewards = EMISSIONS_RATE * 10;
} else if (tokenId > 17500 && tokenId <= 18000) {
presidentRewards = EMISSIONS_RATE * 20;
} else if (tokenId > 18000 && tokenId <= 19000) {
presidentRewards = EMISSIONS_RATE * 50;
} else if (tokenId > 19000 && tokenId <= 20000) {
presidentRewards = EMISSIONS_RATE * 100;
}
uint256 secondsStaked = block.timestamp - tokenIdToTimeStamp[tokenId];
return secondsStaked * presidentRewards;
}
function getStaker(uint256 tokenId) public view returns (address) {
return tokenIdToStaker[tokenId];
}
} | Mapping of president to timestampMapping of president to stakerMapping of staker to president | contract WMC is ERC20Burnable, Ownable {
/$$ /$$ /$$ /$$ /$$$$$$
| $$ /$ | $$| $$$ /$$$ /$$__ $$
| $$ /$$$| $$| $$$$ /$$$$| $$ \__/
| $$/$$ $$ $$| $$ $$/$$ $$| $$
| $$$$_ $$$$| $$ $$$| $$| $$
| $$$/ \ $$$| $$\ $ | $$| $$ $$
| $$/ \ $$| $$ \/ | $$| $$$$$$/
|__/ \__/|__/ |__/ \______/
Minted by the Presidents
using SafeMath for uint256;
uint256 public MAX_WALLET_STAKED = 100;
uint256 public EMISSIONS_RATE = 11574070000000;
uint256 public CLAIM_END_TIME = 1648763999;
address nullAddress = 0x0000000000000000000000000000000000000000;
mapping(uint256 => uint256) internal tokenIdToTimeStamp;
mapping(uint256 => address) internal tokenIdToStaker;
mapping(address => uint256[]) internal stakerToTokenIds;
pragma solidity ^0.8.0;
constructor() ERC20("We Mint Cash", "WMC") {
}
function setWashieAddress(address _washieAddress) public onlyOwner {
washieAddress = _washieAddress;
return;
}
function setAbeAddress(address _abeAddress) public onlyOwner {
abeAddress = _abeAddress;
return;
}
function setHamiltonAddress(address _hamiltonAddress) public onlyOwner {
hamiltonAddress = _hamiltonAddress;
return;
}
function setJacksonAddress(address _jacksonAddress) public onlyOwner {
jacksonAddress = _jacksonAddress;
return;
}
function setGrantAddress(address _grantAddress) public onlyOwner {
grantAddress = _grantAddress;
return;
}
function setBennyAddress(address _bennyAddress) public onlyOwner {
bennyAddress = _bennyAddress;
return;
}
function getTokensStaked(address staker)
public
view
returns (uint256[] memory)
{
return stakerToTokenIds[staker];
}
function remove(address staker, uint256 index) internal {
if (index >= stakerToTokenIds[staker].length) return;
for (uint256 i = index; i < stakerToTokenIds[staker].length - 1; i++) {
stakerToTokenIds[staker][i] = stakerToTokenIds[staker][i + 1];
}
stakerToTokenIds[staker].pop();
}
function remove(address staker, uint256 index) internal {
if (index >= stakerToTokenIds[staker].length) return;
for (uint256 i = index; i < stakerToTokenIds[staker].length - 1; i++) {
stakerToTokenIds[staker][i] = stakerToTokenIds[staker][i + 1];
}
stakerToTokenIds[staker].pop();
}
function removeTokenIdFromStaker(address staker, uint256 tokenId) internal {
for (uint256 i = 0; i < stakerToTokenIds[staker].length; i++) {
if (stakerToTokenIds[staker][i] == tokenId) {
remove(staker, i);
}
}
}
function removeTokenIdFromStaker(address staker, uint256 tokenId) internal {
for (uint256 i = 0; i < stakerToTokenIds[staker].length; i++) {
if (stakerToTokenIds[staker][i] == tokenId) {
remove(staker, i);
}
}
}
function removeTokenIdFromStaker(address staker, uint256 tokenId) internal {
for (uint256 i = 0; i < stakerToTokenIds[staker].length; i++) {
if (stakerToTokenIds[staker][i] == tokenId) {
remove(staker, i);
}
}
}
function stakeByIds(uint256[] memory tokenIds) public {
require(
stakerToTokenIds[msg.sender].length + tokenIds.length <=
MAX_WALLET_STAKED,
"Must have less than 31 presidents staked!"
);
address prez;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
prez = washieAddress ;
prez = abeAddress;
prez = hamiltonAddress;
prez = jacksonAddress;
prez = grantAddress;
prez = bennyAddress;
}
require(
IERC721(prez).ownerOf(tokenIds[i]) == msg.sender
&&
tokenIdToStaker[tokenIds[i]] == nullAddress,
"Token must be stakable by you!"
);
IERC721(prez).transferFrom(
msg.sender,
address(this),
tokenIds[i]
);
stakerToTokenIds[msg.sender].push(tokenIds[i]);
tokenIdToTimeStamp[tokenIds[i]] = block.timestamp;
tokenIdToStaker[tokenIds[i]] = msg.sender;
}
}
function stakeByIds(uint256[] memory tokenIds) public {
require(
stakerToTokenIds[msg.sender].length + tokenIds.length <=
MAX_WALLET_STAKED,
"Must have less than 31 presidents staked!"
);
address prez;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
prez = washieAddress ;
prez = abeAddress;
prez = hamiltonAddress;
prez = jacksonAddress;
prez = grantAddress;
prez = bennyAddress;
}
require(
IERC721(prez).ownerOf(tokenIds[i]) == msg.sender
&&
tokenIdToStaker[tokenIds[i]] == nullAddress,
"Token must be stakable by you!"
);
IERC721(prez).transferFrom(
msg.sender,
address(this),
tokenIds[i]
);
stakerToTokenIds[msg.sender].push(tokenIds[i]);
tokenIdToTimeStamp[tokenIds[i]] = block.timestamp;
tokenIdToStaker[tokenIds[i]] = msg.sender;
}
}
function stakeByIds(uint256[] memory tokenIds) public {
require(
stakerToTokenIds[msg.sender].length + tokenIds.length <=
MAX_WALLET_STAKED,
"Must have less than 31 presidents staked!"
);
address prez;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
prez = washieAddress ;
prez = abeAddress;
prez = hamiltonAddress;
prez = jacksonAddress;
prez = grantAddress;
prez = bennyAddress;
}
require(
IERC721(prez).ownerOf(tokenIds[i]) == msg.sender
&&
tokenIdToStaker[tokenIds[i]] == nullAddress,
"Token must be stakable by you!"
);
IERC721(prez).transferFrom(
msg.sender,
address(this),
tokenIds[i]
);
stakerToTokenIds[msg.sender].push(tokenIds[i]);
tokenIdToTimeStamp[tokenIds[i]] = block.timestamp;
tokenIdToStaker[tokenIds[i]] = msg.sender;
}
}
} else if (tokenIds[i] > 10000 && tokenIds[i] <= 15000) {
} else if (tokenIds[i] > 15000 && tokenIds[i] <= 17500) {
} else if (tokenIds[i] > 17500 && tokenIds[i] <= 18000) {
} else if (tokenIds[i] > 18000 && tokenIds[i] <= 19000) {
} else if (tokenIds[i] > 19000 && tokenIds[i] <= 20000) {
function unstakeAll() public {
require(
stakerToTokenIds[msg.sender].length > 0,
"Must have at least one token staked!"
);
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
address prez;
for (uint256 i = stakerToTokenIds[msg.sender].length; i > 0; i--) {
uint256 tokenId = stakerToTokenIds[msg.sender][i - 1];
if (tokenId <= 10000) {
prez = washieAddress;
presidentEmissions = EMISSIONS_RATE;
prez = abeAddress;
presidentEmissions = EMISSIONS_RATE * 5;
prez = hamiltonAddress;
presidentEmissions = EMISSIONS_RATE * 10;
prez = jacksonAddress;
presidentEmissions = EMISSIONS_RATE * 20;
prez = grantAddress;
presidentEmissions = EMISSIONS_RATE * 50;
prez = bennyAddress;
presidentEmissions = EMISSIONS_RATE * 100;
}
IERC721(prez).transferFrom(
address(this),
msg.sender,
tokenId
);
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenId]) *
presidentEmissions);
removeTokenIdFromStaker(msg.sender, tokenId);
tokenIdToStaker[tokenId] = nullAddress;
_mint(msg.sender, totalRewards);
}
}
function unstakeAll() public {
require(
stakerToTokenIds[msg.sender].length > 0,
"Must have at least one token staked!"
);
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
address prez;
for (uint256 i = stakerToTokenIds[msg.sender].length; i > 0; i--) {
uint256 tokenId = stakerToTokenIds[msg.sender][i - 1];
if (tokenId <= 10000) {
prez = washieAddress;
presidentEmissions = EMISSIONS_RATE;
prez = abeAddress;
presidentEmissions = EMISSIONS_RATE * 5;
prez = hamiltonAddress;
presidentEmissions = EMISSIONS_RATE * 10;
prez = jacksonAddress;
presidentEmissions = EMISSIONS_RATE * 20;
prez = grantAddress;
presidentEmissions = EMISSIONS_RATE * 50;
prez = bennyAddress;
presidentEmissions = EMISSIONS_RATE * 100;
}
IERC721(prez).transferFrom(
address(this),
msg.sender,
tokenId
);
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenId]) *
presidentEmissions);
removeTokenIdFromStaker(msg.sender, tokenId);
tokenIdToStaker[tokenId] = nullAddress;
_mint(msg.sender, totalRewards);
}
}
function unstakeAll() public {
require(
stakerToTokenIds[msg.sender].length > 0,
"Must have at least one token staked!"
);
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
address prez;
for (uint256 i = stakerToTokenIds[msg.sender].length; i > 0; i--) {
uint256 tokenId = stakerToTokenIds[msg.sender][i - 1];
if (tokenId <= 10000) {
prez = washieAddress;
presidentEmissions = EMISSIONS_RATE;
prez = abeAddress;
presidentEmissions = EMISSIONS_RATE * 5;
prez = hamiltonAddress;
presidentEmissions = EMISSIONS_RATE * 10;
prez = jacksonAddress;
presidentEmissions = EMISSIONS_RATE * 20;
prez = grantAddress;
presidentEmissions = EMISSIONS_RATE * 50;
prez = bennyAddress;
presidentEmissions = EMISSIONS_RATE * 100;
}
IERC721(prez).transferFrom(
address(this),
msg.sender,
tokenId
);
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenId]) *
presidentEmissions);
removeTokenIdFromStaker(msg.sender, tokenId);
tokenIdToStaker[tokenId] = nullAddress;
_mint(msg.sender, totalRewards);
}
}
} else if (tokenId > 10000 && tokenId <= 15000) {
} else if (tokenId > 15000 && tokenId <= 17500) {
} else if (tokenId > 17500 && tokenId <= 18000) {
} else if (tokenId > 18000 && tokenId <= 19000) {
} else if (tokenId > 19000 && tokenId <= 20000) {
function unstakeByIds(uint256[] memory tokenIds) public {
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
address prez;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
prez = washieAddress;
presidentEmissions = EMISSIONS_RATE;
prez = abeAddress;
presidentEmissions = EMISSIONS_RATE * 5;
prez = hamiltonAddress;
presidentEmissions = EMISSIONS_RATE * 10;
prez = jacksonAddress;
presidentEmissions = EMISSIONS_RATE * 20;
prez = grantAddress;
presidentEmissions = EMISSIONS_RATE * 50;
prez = bennyAddress;
presidentEmissions = EMISSIONS_RATE * 100;
}
require(
tokenIdToStaker[tokenIds[i]] == msg.sender,
"Message Sender was not original staker!"
);
IERC721(prez).transferFrom(
address(this),
msg.sender,
tokenIds[i]
);
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
removeTokenIdFromStaker(msg.sender, tokenIds[i]);
tokenIdToStaker[tokenIds[i]] = nullAddress;
_mint(msg.sender, totalRewards);
}
}
function unstakeByIds(uint256[] memory tokenIds) public {
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
address prez;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
prez = washieAddress;
presidentEmissions = EMISSIONS_RATE;
prez = abeAddress;
presidentEmissions = EMISSIONS_RATE * 5;
prez = hamiltonAddress;
presidentEmissions = EMISSIONS_RATE * 10;
prez = jacksonAddress;
presidentEmissions = EMISSIONS_RATE * 20;
prez = grantAddress;
presidentEmissions = EMISSIONS_RATE * 50;
prez = bennyAddress;
presidentEmissions = EMISSIONS_RATE * 100;
}
require(
tokenIdToStaker[tokenIds[i]] == msg.sender,
"Message Sender was not original staker!"
);
IERC721(prez).transferFrom(
address(this),
msg.sender,
tokenIds[i]
);
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
removeTokenIdFromStaker(msg.sender, tokenIds[i]);
tokenIdToStaker[tokenIds[i]] = nullAddress;
_mint(msg.sender, totalRewards);
}
}
function unstakeByIds(uint256[] memory tokenIds) public {
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
address prez;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
prez = washieAddress;
presidentEmissions = EMISSIONS_RATE;
prez = abeAddress;
presidentEmissions = EMISSIONS_RATE * 5;
prez = hamiltonAddress;
presidentEmissions = EMISSIONS_RATE * 10;
prez = jacksonAddress;
presidentEmissions = EMISSIONS_RATE * 20;
prez = grantAddress;
presidentEmissions = EMISSIONS_RATE * 50;
prez = bennyAddress;
presidentEmissions = EMISSIONS_RATE * 100;
}
require(
tokenIdToStaker[tokenIds[i]] == msg.sender,
"Message Sender was not original staker!"
);
IERC721(prez).transferFrom(
address(this),
msg.sender,
tokenIds[i]
);
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
removeTokenIdFromStaker(msg.sender, tokenIds[i]);
tokenIdToStaker[tokenIds[i]] = nullAddress;
_mint(msg.sender, totalRewards);
}
}
} else if (tokenIds[i] > 10000 && tokenIds[i] <= 15000) {
} else if (tokenIds[i] > 15000 && tokenIds[i] <= 17500) {
} else if (tokenIds[i] > 17500 && tokenIds[i] <= 18000) {
} else if (tokenIds[i] > 18000 && tokenIds[i] <= 19000) {
} else if (tokenIds[i] > 19000 && tokenIds[i] <= 20000) {
function claimByTokenId(uint256 tokenId) public {
require(
tokenIdToStaker[tokenId] == msg.sender,
"Token is not claimable by you!"
);
require(block.timestamp < CLAIM_END_TIME, "Claim period is over!");
uint256 presidentEmissions = 0;
if (tokenId <= 10000) {
presidentEmissions = EMISSIONS_RATE;
presidentEmissions = EMISSIONS_RATE * 5;
presidentEmissions = EMISSIONS_RATE * 10;
presidentEmissions = EMISSIONS_RATE * 20;
presidentEmissions = EMISSIONS_RATE * 50;
presidentEmissions = EMISSIONS_RATE * 100;
}
_mint(
msg.sender,
((block.timestamp - tokenIdToTimeStamp[tokenId]) * presidentEmissions)
);
tokenIdToTimeStamp[tokenId] = block.timestamp;
}
function claimByTokenId(uint256 tokenId) public {
require(
tokenIdToStaker[tokenId] == msg.sender,
"Token is not claimable by you!"
);
require(block.timestamp < CLAIM_END_TIME, "Claim period is over!");
uint256 presidentEmissions = 0;
if (tokenId <= 10000) {
presidentEmissions = EMISSIONS_RATE;
presidentEmissions = EMISSIONS_RATE * 5;
presidentEmissions = EMISSIONS_RATE * 10;
presidentEmissions = EMISSIONS_RATE * 20;
presidentEmissions = EMISSIONS_RATE * 50;
presidentEmissions = EMISSIONS_RATE * 100;
}
_mint(
msg.sender,
((block.timestamp - tokenIdToTimeStamp[tokenId]) * presidentEmissions)
);
tokenIdToTimeStamp[tokenId] = block.timestamp;
}
} else if (tokenId > 10000 && tokenId <= 15000) {
} else if (tokenId > 15000 && tokenId <= 17500) {
} else if (tokenId > 17500 && tokenId <= 18000) {
} else if (tokenId > 18000 && tokenId <= 19000) {
} else if (tokenId > 19000 && tokenId <= 20000) {
function claimAll() public {
require(block.timestamp < CLAIM_END_TIME, "Claim period is over!");
uint256[] memory tokenIds = stakerToTokenIds[msg.sender];
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
tokenIdToStaker[tokenIds[i]] == msg.sender,
"Token is not claimable by you!"
);
if (tokenIds[i] <= 10000) {
presidentEmissions = EMISSIONS_RATE;
presidentEmissions = EMISSIONS_RATE * 5;
presidentEmissions = EMISSIONS_RATE * 10;
presidentEmissions = EMISSIONS_RATE * 20;
presidentEmissions = EMISSIONS_RATE * 50;
presidentEmissions = EMISSIONS_RATE * 100;
}
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
tokenIdToTimeStamp[tokenIds[i]] = block.timestamp;
}
_mint(msg.sender, totalRewards);
}
function claimAll() public {
require(block.timestamp < CLAIM_END_TIME, "Claim period is over!");
uint256[] memory tokenIds = stakerToTokenIds[msg.sender];
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
tokenIdToStaker[tokenIds[i]] == msg.sender,
"Token is not claimable by you!"
);
if (tokenIds[i] <= 10000) {
presidentEmissions = EMISSIONS_RATE;
presidentEmissions = EMISSIONS_RATE * 5;
presidentEmissions = EMISSIONS_RATE * 10;
presidentEmissions = EMISSIONS_RATE * 20;
presidentEmissions = EMISSIONS_RATE * 50;
presidentEmissions = EMISSIONS_RATE * 100;
}
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
tokenIdToTimeStamp[tokenIds[i]] = block.timestamp;
}
_mint(msg.sender, totalRewards);
}
function claimAll() public {
require(block.timestamp < CLAIM_END_TIME, "Claim period is over!");
uint256[] memory tokenIds = stakerToTokenIds[msg.sender];
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
require(
tokenIdToStaker[tokenIds[i]] == msg.sender,
"Token is not claimable by you!"
);
if (tokenIds[i] <= 10000) {
presidentEmissions = EMISSIONS_RATE;
presidentEmissions = EMISSIONS_RATE * 5;
presidentEmissions = EMISSIONS_RATE * 10;
presidentEmissions = EMISSIONS_RATE * 20;
presidentEmissions = EMISSIONS_RATE * 50;
presidentEmissions = EMISSIONS_RATE * 100;
}
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
tokenIdToTimeStamp[tokenIds[i]] = block.timestamp;
}
_mint(msg.sender, totalRewards);
}
} else if (tokenIds[i] > 10000 && tokenIds[i] <= 15000) {
} else if (tokenIds[i] > 15000 && tokenIds[i] <= 17500) {
} else if (tokenIds[i] > 17500 && tokenIds[i] <= 18000) {
} else if (tokenIds[i] > 18000 && tokenIds[i] <= 19000) {
} else if (tokenIds[i] > 19000 && tokenIds[i] <= 20000) {
function getAllRewards(address staker) public view returns (uint256) {
uint256[] memory tokenIds = stakerToTokenIds[staker];
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
presidentEmissions = EMISSIONS_RATE;
presidentEmissions = EMISSIONS_RATE * 5;
presidentEmissions = EMISSIONS_RATE * 10;
presidentEmissions = EMISSIONS_RATE * 20;
presidentEmissions = EMISSIONS_RATE * 50;
presidentEmissions = EMISSIONS_RATE * 100;
}
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
}
return totalRewards;
}
function getAllRewards(address staker) public view returns (uint256) {
uint256[] memory tokenIds = stakerToTokenIds[staker];
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
presidentEmissions = EMISSIONS_RATE;
presidentEmissions = EMISSIONS_RATE * 5;
presidentEmissions = EMISSIONS_RATE * 10;
presidentEmissions = EMISSIONS_RATE * 20;
presidentEmissions = EMISSIONS_RATE * 50;
presidentEmissions = EMISSIONS_RATE * 100;
}
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
}
return totalRewards;
}
function getAllRewards(address staker) public view returns (uint256) {
uint256[] memory tokenIds = stakerToTokenIds[staker];
uint256 totalRewards = 0;
uint256 presidentEmissions = 0;
for (uint256 i = 0; i < tokenIds.length; i++) {
if (tokenIds[i] <= 10000) {
presidentEmissions = EMISSIONS_RATE;
presidentEmissions = EMISSIONS_RATE * 5;
presidentEmissions = EMISSIONS_RATE * 10;
presidentEmissions = EMISSIONS_RATE * 20;
presidentEmissions = EMISSIONS_RATE * 50;
presidentEmissions = EMISSIONS_RATE * 100;
}
totalRewards =
totalRewards +
((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) *
presidentEmissions);
}
return totalRewards;
}
} else if (tokenIds[i] > 10000 && tokenIds[i] <= 15000) {
} else if (tokenIds[i] > 15000 && tokenIds[i] <= 17500) {
} else if (tokenIds[i] > 17500 && tokenIds[i] <= 18000) {
} else if (tokenIds[i] > 18000 && tokenIds[i] <= 19000) {
} else if (tokenIds[i] > 19000 && tokenIds[i] <= 20000) {
function getRewardsByTokenId(uint256 tokenId)
public
view
returns (uint256)
{
require(
tokenIdToStaker[tokenId] != nullAddress,
"Token is not staked!"
);
uint256 presidentRewards = 0;
if (tokenId <= 10000) {
presidentRewards = EMISSIONS_RATE;
presidentRewards = EMISSIONS_RATE * 5;
presidentRewards = EMISSIONS_RATE * 10;
presidentRewards = EMISSIONS_RATE * 20;
presidentRewards = EMISSIONS_RATE * 50;
presidentRewards = EMISSIONS_RATE * 100;
}
uint256 secondsStaked = block.timestamp - tokenIdToTimeStamp[tokenId];
return secondsStaked * presidentRewards;
}
function getRewardsByTokenId(uint256 tokenId)
public
view
returns (uint256)
{
require(
tokenIdToStaker[tokenId] != nullAddress,
"Token is not staked!"
);
uint256 presidentRewards = 0;
if (tokenId <= 10000) {
presidentRewards = EMISSIONS_RATE;
presidentRewards = EMISSIONS_RATE * 5;
presidentRewards = EMISSIONS_RATE * 10;
presidentRewards = EMISSIONS_RATE * 20;
presidentRewards = EMISSIONS_RATE * 50;
presidentRewards = EMISSIONS_RATE * 100;
}
uint256 secondsStaked = block.timestamp - tokenIdToTimeStamp[tokenId];
return secondsStaked * presidentRewards;
}
} else if (tokenId > 10000 && tokenId <= 15000) {
} else if (tokenId > 15000 && tokenId <= 17500) {
} else if (tokenId > 17500 && tokenId <= 18000) {
} else if (tokenId > 18000 && tokenId <= 19000) {
} else if (tokenId > 19000 && tokenId <= 20000) {
function getStaker(uint256 tokenId) public view returns (address) {
return tokenIdToStaker[tokenId];
}
} | 6,420,733 | [
1,
3233,
434,
4075,
6392,
358,
2858,
3233,
434,
4075,
6392,
358,
384,
6388,
3233,
434,
384,
6388,
358,
4075,
6392,
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,
16351,
678,
20022,
353,
4232,
39,
3462,
38,
321,
429,
16,
14223,
6914,
288,
203,
342,
16547,
1377,
342,
16547,
342,
16547,
1377,
342,
16547,
225,
342,
16547,
16547,
16547,
225,
203,
96,
5366,
225,
342,
8,
571,
5366,
96,
5366,
8,
565,
342,
16547,
8,
342,
16547,
972,
225,
5366,
203,
96,
5366,
342,
16547,
8,
96,
5366,
96,
5366,
16547,
225,
342,
16547,
16547,
96,
5366,
225,
521,
972,
19,
203,
96,
5366,
11141,
8,
5366,
5366,
96,
5366,
5366,
11141,
8,
5366,
96,
5366,
4202,
203,
96,
5366,
16547,
67,
225,
5366,
16547,
96,
5366,
225,
5366,
8,
96,
5366,
96,
5366,
4202,
203,
96,
5366,
13209,
521,
225,
5366,
8,
96,
5366,
64,
225,
271,
571,
5366,
96,
5366,
565,
5366,
203,
96,
5366,
19,
282,
521,
225,
5366,
96,
5366,
18368,
225,
571,
5366,
96,
225,
5366,
16547,
8,
13209,
203,
96,
972,
19,
377,
521,
972,
19,
96,
972,
19,
377,
571,
972,
19,
521,
7198,
972,
19,
7010,
28524,
5411,
203,
4766,
1171,
490,
474,
329,
635,
326,
453,
15567,
4877,
203,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
1071,
4552,
67,
59,
1013,
15146,
67,
882,
14607,
2056,
273,
2130,
31,
203,
565,
2254,
5034,
1071,
7141,
45,
4475,
55,
67,
24062,
273,
22821,
5608,
8642,
17877,
31,
203,
565,
2254,
5034,
1071,
29859,
3445,
67,
4415,
67,
4684,
273,
404,
1105,
11035,
4449,
11984,
31,
203,
203,
565,
1758,
446,
1887,
273,
374,
92,
12648,
12648,
12648,
12648,
2
]
|
//Address: 0x553b4546d26f383d4f4a056b7f50dadff07fb252
//Contract name: BattleOfThermopylae
//Balance: 0 Ether
//Verification Date: 10/19/2017
//Transacion Count: 75
// CODE STARTS HERE
/*******************************************************************************
********************* BATTLE OF THERMOPYLAE v1.1 ***************************
********************************************************************************
Battle smart contract is a platform/ecosystem for gaming built on top of a
decentralized smart contract, allowing anyone to use a Warrior tokens: entities
which exists on the Ethereum Network, which can be traded or used to enter the
battle with other Warrior tokens holders, for profit or just for fun!
********************************************************************************
************************** RULES ***************************
********************************************************************************
- This first battle contract accepts Persians, Spartans (300 Tokens), Immortals
and Athenians as warriors.
- Every warrior token has a proper value in **Battle Point (BP)** that represent
his strength on the battle contract.
- Persians and Immortals represent the Persian faction, Spartans and Athenians
the Greek one.
- During the first phase players send tokens to the battle contract
(NOTE: before calling the proper contract's function that assigning warriors
to the battlefiled, players NEED TO CALL APPROVE on their token contract to
allow Battle contract to move their tokens.
- Once sent, troops can't be retired form the battlefield
- The battle will last for several days
- When the battle period is over, following results can happpen:
-- When the battle ends in a draw:
(*) 10% of main troops of both sides lie on the ground
(*) 90% of them can be retrieved by each former owner
(*) No slaves are assigned
-- When the battle ends with a winning factions:
(*) 10% of main troops of both sides lie on the ground
(*) 90% of them can be retrieved by each former owner
(*) Surviving warriors of the loosing faction are assigned as slaves
to winners
(*) Slaves are computed based on the BP contributed by each sender
- Persians and Spartans are main troops.
- Immortals and Athenians are support troops: there will be no casualties in
their row, and they will be retrieved without losses by original senders.
- Only Persians and Spartans can be slaves. Immortals and Athenians WILL NOT
be sent back as slaves to winners.
********************************************************************************
************************** TOKEN ADDRESSES ***************************
********************************************************************************
Persians (PRS) 0x163733bcc28dbf26B41a8CfA83e369b5B3af741b
Immortals (IMT) 0x22E5F62D0FA19974749faa194e3d3eF6d89c08d7
Spartans (300) 0xaEc98A708810414878c3BCDF46Aad31dEd4a4557
Athenians (ATH) 0x17052d51E954592C1046320c2371AbaB6C73Ef10
Battles (BTL) Set after the deployment of this contract
*******************************************************************************/
pragma solidity ^0.4.15;
contract TokenEIP20 {
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
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 Timed {
uint256 public startTime; //seconds since Unix epoch time
uint256 public endTime; //seconds since Unix epoch time
uint256 public avarageBlockTime; //seconds
// This check is an helper function for ÐApp to check the effect of the NEXT transaction, NOT simply the current state of the contract
function isInTime() constant returns (bool inTime) {
return block.timestamp >= (startTime - avarageBlockTime) && !isTimeExpired();
}
// This check is an helper function for ÐApp to check the effect of the NEXT transacion, NOT simply the current state of the contract
function isTimeExpired() constant returns (bool timeExpired) {
return block.timestamp + avarageBlockTime >= endTime;
}
modifier onlyIfInTime {
require(block.timestamp >= startTime && block.timestamp <= endTime); _;
}
modifier onlyIfTimePassed {
require(block.timestamp > endTime); _;
}
function Timed(uint256 _startTime, uint256 life, uint8 _avarageBlockTime) {
startTime = _startTime;
endTime = _startTime + life;
avarageBlockTime = _avarageBlockTime;
}
}
library SafeMathLib {
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function add(uint x, uint y) internal returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function per(uint x, uint y) internal constant returns (uint z) {
return mul((x / 100), y);
}
function min(uint x, uint y) internal returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal returns (int z) {
return x >= y ? x : y;
}
function wmul(uint x, uint y) internal returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function wper(uint x, uint y) internal constant returns (uint z) {
return wmul(wdiv(x, 100), y);
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract Owned {
address owner;
function Owned() { owner = msg.sender; }
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract Upgradable is Owned {
string public VERSION;
bool public deprecated;
string public newVersion;
address public newAddress;
function Upgradable(string _version) {
VERSION = _version;
}
function setDeprecated(string _newVersion, address _newAddress) onlyOwner returns (bool success) {
require(!deprecated);
deprecated = true;
newVersion = _newVersion;
newAddress = _newAddress;
return true;
}
}
contract BattleOfThermopylae is Timed, Upgradable {
using SafeMathLib for uint;
uint public constant MAX_PERSIANS = 300000 * 10**18; // 300.000
uint public constant MAX_SPARTANS = 300 * 10**18; // 300
uint public constant MAX_IMMORTALS = 100; // 100
uint public constant MAX_ATHENIANS = 100 * 10**18; // 100
uint8 public constant BP_PERSIAN = 1; // Each Persian worths 1 Battle Point
uint8 public constant BP_IMMORTAL = 100; // Each Immortal worths 100 Battle Points
uint16 public constant BP_SPARTAN = 1000; // Each Spartan worths 1000 Battle Points
uint8 public constant BP_ATHENIAN = 100; // Each Athenians worths 100 Battle Points
uint8 public constant BTL_PERSIAN = 1; // Each Persian worths 1 Battle Token
uint16 public constant BTL_IMMORTAL = 2000; // Each Immortal worths 2000 Battle Tokens
uint16 public constant BTL_SPARTAN = 1000; // Each Spartan worths 1000 Battle Tokens
uint16 public constant BTL_ATHENIAN = 2000; // Each Athenians worths 2000 Battle Tokens
uint public constant WAD = 10**18; // Shortcut for 1.000.000.000.000.000.000
uint8 public constant BATTLE_POINT_DECIMALS = 18; // Battle points decimal positions
uint8 public constant BATTLE_CASUALTIES = 10; // Percentage of Persian and Spartan casualties
address public persians; // Address of the Persian Tokens
address public immortals; // Address of the Immortal Tokens
address public spartans; // Address of the 300 Tokens
address public athenians; // Address of the Athenian Tokens
address public battles; // Address of the Battle Tokens
address public battlesOwner; // Owner of the Battle Token contract
mapping (address => mapping (address => uint)) public warriorsByPlayer; // Troops currently allocated by each player
mapping (address => uint) public warriorsOnTheBattlefield; // Total troops fighting in the battle
event WarriorsAssignedToBattlefield (address indexed _from, address _faction, uint _battlePointsIncrementForecast);
event WarriorsBackToHome (address indexed _to, address _faction, uint _survivedWarriors);
function BattleOfThermopylae(uint _startTime, uint _life, uint8 _avarageBlockTime, address _persians, address _immortals, address _spartans, address _athenians) Timed(_startTime, _life, _avarageBlockTime) Upgradable("1.0.0") {
persians = _persians;
immortals = _immortals;
spartans = _spartans;
athenians = _athenians;
}
function setBattleTokenAddress(address _battleTokenAddress, address _battleTokenOwner) onlyOwner {
battles = _battleTokenAddress;
battlesOwner = _battleTokenOwner;
}
function assignPersiansToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
assignWarriorsToBattle(msg.sender, persians, _warriors, MAX_PERSIANS);
sendBattleTokens(msg.sender, _warriors.mul(BTL_PERSIAN));
// Persians are divisible with 18 decimals and their value is 1 BP
WarriorsAssignedToBattlefield(msg.sender, persians, _warriors / WAD);
return true;
}
function assignImmortalsToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
assignWarriorsToBattle(msg.sender, immortals, _warriors, MAX_IMMORTALS);
sendBattleTokens(msg.sender, _warriors.mul(WAD).mul(BTL_IMMORTAL));
// Immortals are not divisible and their value is 100 BP
WarriorsAssignedToBattlefield(msg.sender, immortals, _warriors.mul(BP_IMMORTAL));
return true;
}
function assignSpartansToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
assignWarriorsToBattle(msg.sender, spartans, _warriors, MAX_SPARTANS);
sendBattleTokens(msg.sender, _warriors.mul(BTL_SPARTAN));
// Spartans are divisible with 18 decimals and their value is 1.000 BP
WarriorsAssignedToBattlefield(msg.sender, spartans, (_warriors / WAD).mul(BP_SPARTAN));
return true;
}
function assignAtheniansToBattle(uint _warriors) onlyIfInTime external returns (bool success) {
assignWarriorsToBattle(msg.sender, athenians, _warriors, MAX_ATHENIANS);
sendBattleTokens(msg.sender, _warriors.mul(BTL_ATHENIAN));
// Athenians are divisible with 18 decimals and their value is 100 BP
WarriorsAssignedToBattlefield(msg.sender, athenians, (_warriors / WAD).mul(BP_ATHENIAN));
return true;
}
function redeemWarriors() onlyIfTimePassed external returns (bool success) {
if (getPersiansBattlePoints() > getGreeksBattlePoints()) {
// Persians won, compute slaves
uint spartanSlaves = computeSlaves(msg.sender, spartans);
if (spartanSlaves > 0) {
// Send back Spartan slaves to winner
sendWarriors(msg.sender, spartans, spartanSlaves);
}
// Send back Persians but casualties
retrieveWarriors(msg.sender, persians, BATTLE_CASUALTIES);
} else if (getPersiansBattlePoints() < getGreeksBattlePoints()) {
//Greeks won, send back Persian slaves
uint persianSlaves = computeSlaves(msg.sender, persians);
if (persianSlaves > 0) {
// Send back Persians slaves to winner
sendWarriors(msg.sender, persians, persianSlaves);
}
// Send back Spartans but casualties
retrieveWarriors(msg.sender, spartans, BATTLE_CASUALTIES);
} else {
// It's a draw, send back Persians and Spartans but casualties
retrieveWarriors(msg.sender, persians, BATTLE_CASUALTIES);
retrieveWarriors(msg.sender, spartans, BATTLE_CASUALTIES);
}
// Send back Immortals untouched
retrieveWarriors(msg.sender, immortals, 0);
// Send back Athenians untouched
retrieveWarriors(msg.sender, athenians, 0);
return true;
}
function assignWarriorsToBattle(address _player, address _faction, uint _warriors, uint _maxWarriors) private {
require(warriorsOnTheBattlefield[_faction].add(_warriors) <= _maxWarriors);
require(TokenEIP20(_faction).transferFrom(_player, address(this), _warriors));
warriorsByPlayer[_player][_faction] = warriorsByPlayer[_player][_faction].add(_warriors);
warriorsOnTheBattlefield[_faction] = warriorsOnTheBattlefield[_faction].add(_warriors);
}
function retrieveWarriors(address _player, address _faction, uint8 _deadPercentage) private {
if (warriorsByPlayer[_player][_faction] > 0) {
uint _warriors = warriorsByPlayer[_player][_faction];
if (_deadPercentage > 0) {
_warriors = _warriors.sub(_warriors.wper(_deadPercentage));
}
warriorsByPlayer[_player][_faction] = 0;
sendWarriors(_player, _faction, _warriors);
WarriorsBackToHome(_player, _faction, _warriors);
}
}
function sendWarriors(address _player, address _faction, uint _warriors) private {
require(TokenEIP20(_faction).transfer(_player, _warriors));
}
function sendBattleTokens(address _player, uint _value) private {
require(TokenEIP20(battles).transferFrom(battlesOwner, _player, _value));
}
function getPersiansOnTheBattlefield(address _player) constant returns (uint persiansOnTheBattlefield) {
return warriorsByPlayer[_player][persians];
}
function getImmortalsOnTheBattlefield(address _player) constant returns (uint immortalsOnTheBattlefield) {
return warriorsByPlayer[_player][immortals];
}
function getSpartansOnTheBattlefield(address _player) constant returns (uint spartansOnTheBattlefield) {
return warriorsByPlayer[_player][spartans];
}
function getAtheniansOnTheBattlefield(address _player) constant returns (uint atheniansOnTheBattlefield) {
return warriorsByPlayer[_player][athenians];
}
function getPersiansBattlePoints() constant returns (uint persiansBattlePoints) {
return (warriorsOnTheBattlefield[persians].mul(BP_PERSIAN) + warriorsOnTheBattlefield[immortals].mul(WAD).mul(BP_IMMORTAL));
}
function getGreeksBattlePoints() constant returns (uint greeksBattlePoints) {
return (warriorsOnTheBattlefield[spartans].mul(BP_SPARTAN) + warriorsOnTheBattlefield[athenians].mul(BP_ATHENIAN));
}
function getPersiansBattlePointsBy(address _player) constant returns (uint playerBattlePoints) {
return (getPersiansOnTheBattlefield(_player).mul(BP_PERSIAN) + getImmortalsOnTheBattlefield(_player).mul(WAD).mul(BP_IMMORTAL));
}
function getGreeksBattlePointsBy(address _player) constant returns (uint playerBattlePoints) {
return (getSpartansOnTheBattlefield(_player).mul(BP_SPARTAN) + getAtheniansOnTheBattlefield(_player).mul(BP_ATHENIAN));
}
function computeSlaves(address _player, address _loosingMainTroops) constant returns (uint slaves) {
if (_loosingMainTroops == spartans) {
return getPersiansBattlePointsBy(_player).wdiv(getPersiansBattlePoints()).wmul(getTotalSlaves(spartans));
} else {
return getGreeksBattlePointsBy(_player).wdiv(getGreeksBattlePoints()).wmul(getTotalSlaves(persians));
}
}
function getTotalSlaves(address _faction) constant returns (uint slaves) {
return warriorsOnTheBattlefield[_faction].sub(warriorsOnTheBattlefield[_faction].wper(BATTLE_CASUALTIES));
}
function isInProgress() constant returns (bool inProgress) {
return !isTimeExpired();
}
function isEnded() constant returns (bool ended) {
return isTimeExpired();
}
function isDraw() constant returns (bool draw) {
return (getPersiansBattlePoints() == getGreeksBattlePoints());
}
function getTemporaryWinningFaction() constant returns (string temporaryWinningFaction) {
if (isDraw()) {
return "It's currently a draw, but the battle is still in progress!";
}
return getPersiansBattlePoints() > getGreeksBattlePoints() ?
"Persians are winning, but the battle is still in progress!" : "Greeks are winning, but the battle is still in progress!";
}
function getWinningFaction() constant returns (string winningFaction) {
if (isInProgress()) {
return "The battle is still in progress";
}
if (isDraw()) {
return "The battle ended in a draw!";
}
return getPersiansBattlePoints() > getGreeksBattlePoints() ? "Persians" : "Greeks";
}
}
| Address of the Battle Tokens
| address public battles; | 5,358,183 | [
1,
1887,
434,
326,
605,
4558,
298,
13899,
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,
1758,
1071,
324,
4558,
1040,
31,
4766,
2868,
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
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.