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 |
---|---|---|---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC721.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract CryptoGamblers is ERC721, Ownable
{
using Strings for string;
using SafeMath for uint;
// Max tokens supply
uint public constant maxSupply = 777;
//_tokenPropertiesString[tokenID-1] = propertiesString
string[maxSupply] private tokenPropertiesString;
// The IPFS hash of token's metadata
string public metadataHash = "";
// Variables used for RNG
uint private nextBlockNumber = 0;
bytes32 private secretHash = 0;
uint private _rngSeed = 0;
uint private seedExpiry = 0;
bool private rngSemaphore = false;
// Whitelist OpenSea proxy contract for easy trading.
address proxyRegistryAddress;
// Events
event SeedInit(address _from, uint _totalSupply, uint _seedExpiry, uint __rngSeed);
event SeedReset(address _from, uint _totalSupply, uint _seedExpiry);
event LotteryFromTo(address indexed _from, address _winner, uint _value, uint _firstTokenId, uint _lastTokenId, string _userInput, uint indexed _luckyNumber);
event LotteryProperties(address indexed _from, address _winner, uint _value, string _propertiesString, string _userInput, uint indexed _luckyNumber);
constructor() ERC721("CryptoGamblers", "GAMBLERS")
{
proxyRegistryAddress = address(0xa5409ec958C83C3f309868babACA7c86DCB077c1);
ERC721._setBaseURI("https://meta.cryptogamblers.life/gamblers/");
}
function mint(string memory properties) public onlyOwner
{
require(totalSupply() < maxSupply, "Exceeds max supply");
require(seedExpiry > totalSupply(), "_rngSeed expired");
require(rngSemaphore == false, "secret is not revealed");
uint newTokenId = totalSupply().add(1);
if(newTokenId != maxSupply)
{
properties = generateRandomProperties();
}
else
{
// the special one
require(properties.strMatch("??????????????"));
}
_mint(owner(), newTokenId);
tokenPropertiesString[newTokenId-1] = properties;
}
function setMetadataHash(string memory hash) public onlyOwner
{
// modifications are not allowed
require(bytes(metadataHash).length == 0 && totalSupply() == maxSupply);
metadataHash = hash;
}
// public getters
function propertiesOf(uint tokenId) public view returns (string memory)
{
require(tokenId >= 1 && tokenId <= totalSupply());
return tokenPropertiesString[tokenId-1];
}
function getGamblersByProperties(string memory properties) public view returns(uint[] memory, uint)
{
uint[] memory participants = new uint[](totalSupply());
uint participants_count = 0;
for(uint i=0;i<totalSupply();i++)
{
if(tokenPropertiesString[i].strMatch(properties))
{
participants[participants_count++] = i+1;
}
}
return (participants, participants_count);
}
// RNG functions ownerOnly
// probability sheet : https://ipfs.io/ipfs/QmPTm2MvYTHjoSQZSJY5SErGaEL3soje7QpcaqFntwkGno
function generateRandomProperties() internal returns(string memory)
{
// prob(id_0) = (prob_arr[1] - prob_arr[0]) / prob_arr[prob_arr.length - 1]
// prob(id_1) = (prob_arr[2] - prob_arr[1]) / prob_arr[prob_arr.length - 1] ....
uint[] memory hat_hair = new uint[](9);
hat_hair[0] = 0;
hat_hair[1] = 7; // Blank - 7.00%
hat_hair[2] = 22; // Cilinder - 15.00%
hat_hair[3] = 35; // Fallout - 13.00%
hat_hair[4] = 46; // Jokerstars - 11.00%
hat_hair[5] = 61; // Leverage - 15.00%
hat_hair[6] = 73; // Peaky Blinder - 12.00%
hat_hair[7] = 92; // Pump & Dump - 19.00%
hat_hair[8] = 100; // SquidFi Hat - 8.00%
uint[] memory skin_color_facial_expression = new uint[](22);
skin_color_facial_expression[0] = 0;
skin_color_facial_expression[1] = 0; // Blank - 0.00%
skin_color_facial_expression[2] = 17; // Ape Bronze - 1.70%
skin_color_facial_expression[3] = 24; // Ape Red - 0.70%
skin_color_facial_expression[4] = 84; // Black Ecstatic - 6.00%
skin_color_facial_expression[5] = 144; // Black Frustrated - 6.00%
skin_color_facial_expression[6] = 204; // Black Rage - 6.00%
skin_color_facial_expression[7] = 264; // Black Devastated - 6.00%
skin_color_facial_expression[8] = 271; // Golden Pepe - 0.70%
skin_color_facial_expression[9] = 288; // Green Pepe - 1.70%
skin_color_facial_expression[10] = 348; // White Devastated 6.00%
skin_color_facial_expression[11] = 408; // White Ecstatic 6.00%
skin_color_facial_expression[12] = 468; // White Frustrated 6.00%
skin_color_facial_expression[13] = 528;// White Rage 6.00%
skin_color_facial_expression[14] = 588; // Yellow Devastated 6.00%
skin_color_facial_expression[15] = 648; // Yellow Excited 6.00%
skin_color_facial_expression[16] = 708; // Yellow Frustrated 6.00%
skin_color_facial_expression[17] = 768; // Yellow Happy 6.00%
skin_color_facial_expression[18] = 826; // Zombie Happy 5.80%
skin_color_facial_expression[19] = 884; // Zombie Devastated 5.80%
skin_color_facial_expression[20] = 942; // Zombie Ecstatic 5.80%
skin_color_facial_expression[21] = 1000; // Zombie Rage 5.80%
uint[] memory neck = new uint[](8);
neck[0] = 0;
neck[1] = 70; // Blank - 7.00%
neck[2] = 127; // Golden chain - 5.70%
neck[3] = 397; // Horseshoe -27.00%
neck[4] = 577; // Ledger - 18.00%
neck[5] = 723; // Lucky Clover - 14.60%
neck[6] = 873; // Piggy Bank - 15.00%
neck[7] = 1000; // Silver chain - 12.70%
uint[] memory upper_body = new uint[](10);
upper_body[0] = 0;
upper_body[1] = 7; // Blank - 7.00%
upper_body[2] = 17; // 9 to 5 Shirt - 10.00%
upper_body[3] = 23; // ChimsCoin T-shirt - 6.00%
upper_body[4] = 38;// Coinface Jacket -15.00%
upper_body[5] = 48; // Hawaii Shirt - 10.00%
upper_body[6] = 58; // Hoodie Lose365 - 10.00%
upper_body[7] = 66; // Lumber-Gambler Shirt - 8.00%
upper_body[8] = 80; // Tuxedo Top - 14.00%
upper_body[9] = 100; // Uniswamp degen T-shirt - 20.00%
uint[] memory lower_body = new uint[](8);
lower_body[0] = 0;
lower_body[1] = 7; // Blank - 7.00%
lower_body[2] = 19; // Baggy Jeans - 12.00%
lower_body[3] = 35; // Blue Jeans - 16.00%
lower_body[4] = 51; // Colorful Shorts - 16.00%
lower_body[5] = 60; // Ripped Jeans - 9.00%
lower_body[6] = 85; // Sports Pants - 25.00%
lower_body[7] = 100;// Tuxedo Pants - 15.00%
uint[] memory shoes = new uint[](8);
shoes[0] = 0;
shoes[1] = 7; // Blank - 7.00%
shoes[2] = 23; // Cowboy Boots - 16.00%
shoes[3] = 43; // Crocs - 20.00%
shoes[4] = 51; // Fancy Sneakers - 8.00%
shoes[5] = 55; // Lux Flip Flops - 4.00%
shoes[6] = 80; // Old Sneakers - 25.00%
shoes[7] = 100; //Oxfords - 20.00%
uint[] memory attributes = new uint[](26);
attributes[0] = 0;
attributes[1] = 0; // Blank - 0.00%
attributes[2] = 100; // Cone (left hand) - 10.00%
attributes[3] = 200; // Fishing pole (right hand) - 10.00%
attributes[4] = 220; // Fishing pole (right hand) + Cone (left hand) - 2.00%
attributes[5] = 230; // Fishing pole (right hand) + Golden watch (left hand) - 1.00%
attributes[6] = 250; // Fishing pole (right hand) + Joint (left hand) - 2.00%
attributes[7] = 255; // Fishing pole(right hand) + OpenOcean bag (left hand) - 0.50%
attributes[8] = 355; // Golden watch (left hand) - 10.00%
attributes[9] = 455; // Gun (right hand) - 10.00%
attributes[10] = 555; // Joint (left hand) - 10.00%
attributes[11] = 655; // Money bills (right hand) - 10.00%
attributes[12] = 670; // Money bills (right hand) + Cone (left hand) - 1.50%
attributes[13] = 690; // Money bills (right hand) + Golden watch (left hand) - 2.00%
attributes[14] = 695; // Money bills (right hand) + Joint (left hand) - 0.50%
attributes[15] = 715; // Money bills (right hand) + OpenOcean bag (left hand) - 2.00%
attributes[16] = 815; // OpenOcean bag (left hand) - 10.00%
attributes[17] = 915; // Phone (right hand) - 10.00%
attributes[18] = 920; // Phone (right hand) + Cone (left hand) - 0.50%
attributes[19] = 935; // Phone (right hand) + Golden watch (left hand) - 1.50%
attributes[20] = 950; // Phone (right hand) + Joint (left hand) - 1.50%
attributes[21] = 965; // Phone (right hand) + OpenOcean bag (left hand) - 1.50%
attributes[22] = 975; // Pistol (right hand) + Cone (left hand) - 1.00%
attributes[23] = 980; // Pistol (right hand) + Golden watch (left hand) - 0.50%
attributes[24] = 990; // Pistol (right hand) + Joint (left hand) - 1.00%
attributes[25] = 1000; //Pistol (right hand) + OpenOcean bag (left hand) - 1.00%
return string(abi.encodePacked( Strings.uintToPad2Str(upperBound(hat_hair, randomUint(randomSeed(), hat_hair[hat_hair.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(skin_color_facial_expression, randomUint(randomSeed(), skin_color_facial_expression[skin_color_facial_expression.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(neck, randomUint(randomSeed(), neck[neck.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(upper_body, randomUint(randomSeed(), upper_body[upper_body.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(lower_body, randomUint(randomSeed(), lower_body[lower_body.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(shoes, randomUint(randomSeed(), shoes[shoes.length - 1])) - 1),
Strings.uintToPad2Str(upperBound(attributes, randomUint(randomSeed(), attributes[attributes.length - 1])) - 1)));
}
function sendSecretHash(bytes32 _secretHash, uint count) public onlyOwner
{
require(rngSemaphore == false && seedExpiry == totalSupply() && count > 0);
secretHash = _secretHash;
seedExpiry = count.add(totalSupply());
nextBlockNumber = block.number + 1;
rngSemaphore = true;
}
function initRng(string memory secret) public onlyOwner
{
require(rngSemaphore == true && block.number >= nextBlockNumber);
require(keccak256(abi.encodePacked(secret)) == secretHash, "wrong secret");
_rngSeed = uint(keccak256(abi.encodePacked(secret, blockhash(nextBlockNumber))));
rngSemaphore = false;
emit SeedInit(msg.sender, totalSupply(), seedExpiry, _rngSeed);
}
function resetRng() public onlyOwner
{ // we should never call this function
require(rngSemaphore == true);
// event trigger
emit SeedReset(msg.sender, totalSupply(), seedExpiry);
seedExpiry = totalSupply();
rngSemaphore = false;
}
function randomSeed() internal returns (uint)
{
//unchecked
// {
_rngSeed = _rngSeed + 1;
// }
return _rngSeed;
}
// RNG functions public
function randomUint(uint seed, uint modulo) internal pure returns (uint)
{
uint num;
uint nonce = 0;
do
{
num = uint(keccak256(abi.encodePacked(seed, nonce++ )));
}
while( num >= type(uint).max - (type(uint).max.mod(modulo)) );
return num.mod(modulo);
}
// Lottery functions, Off chain randomness : seed = Hash(userSeed + blockhash(currBlockNumber-7))
function tipRandomGambler(uint firstTokenId, uint lastTokenId, string memory userSeed) public payable
{
require(msg.value != 0, "Send some ether" );
require(firstTokenId >= 1 && lastTokenId <= totalSupply() && lastTokenId.sub(firstTokenId) > 0, "Invalid arguments");
uint winner = firstTokenId.add(randomUint(uint(keccak256(abi.encodePacked(userSeed, blockhash(block.number - 7)))), lastTokenId.sub(firstTokenId).add(1)));
address winnerOwner = ownerOf(winner);
payable(winnerOwner).transfer(msg.value);
emit LotteryFromTo(msg.sender, winnerOwner, msg.value, firstTokenId, lastTokenId, userSeed, winner);
}
function tipRandomGambler(string memory userSeed) public payable
{
tipRandomGambler(1, totalSupply(), userSeed);
}
function tipRandomGambler(string memory properties, string memory userSeed) public payable
{
require(msg.value != 0, "Send some ether" );
require(properties.strMatch("??????????????"), "Invalid arguments");
(uint[] memory participants, uint participants_count) = getGamblersByProperties(properties);
require(participants_count != 0, "No participants");
uint winner = participants[randomUint(uint(keccak256(abi.encodePacked(userSeed, blockhash(block.number - 7)))), participants_count)];
address winnerOwner = ownerOf(winner);
payable(winnerOwner).transfer(msg.value);
emit LotteryProperties(msg.sender, winnerOwner, msg.value, properties, userSeed, winner);
}
// Binary search
function upperBound(uint[] memory arr, uint value) internal pure returns(uint)
{
uint mid;
uint low = 0;
uint high = arr.length;
while (low < high)
{
mid = low + (high - low) / 2;
if (value >= arr[mid])
low = mid + 1;
else
high = mid;
}
return low;
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
} | Pistol (right hand) + Golden watch (left hand) - 0.50%
| attributes[23] = 980; | 11,771,301 | [
1,
52,
376,
355,
261,
4083,
948,
13,
397,
611,
1673,
275,
4267,
261,
4482,
948,
13,
300,
374,
18,
3361,
9,
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,
3639,
1677,
63,
4366,
65,
273,
2468,
3672,
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
] |
./full_match/42/0x28D2288e605A077DBfD8A23E77a41Af1B923BE0c/sources/browser/FluxCampacitar.sol | * Set rewards portion for stakers in rewards amount. ex: 98 => 98% (2% for dev)/ | function setRewardFee(uint256 rewardFee) external onlyOwner returns (bool) {
require(
rewardFee >= 96 && rewardFee <= 100,
"FluxCampacitor: reward fee should be in 96 ~ 100."
);
_rewardFee = rewardFee;
return true;
}
| 9,585,896 | [
1,
694,
283,
6397,
14769,
364,
384,
581,
414,
316,
283,
6397,
3844,
18,
431,
30,
24645,
516,
24645,
9,
261,
22,
9,
364,
4461,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
444,
17631,
1060,
14667,
12,
11890,
5034,
19890,
14667,
13,
3903,
1338,
5541,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
203,
5411,
19890,
14667,
1545,
19332,
597,
19890,
14667,
1648,
2130,
16,
203,
5411,
315,
2340,
2616,
39,
931,
1077,
1811,
30,
19890,
14036,
1410,
506,
316,
19332,
4871,
2130,
1199,
203,
3639,
11272,
203,
203,
3639,
389,
266,
2913,
14667,
273,
19890,
14667,
31,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./owned.sol";
import "./StopTheWarOnDrugs.sol";
import "./context.sol";
import "./address-utils.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract SWDMarketPlace is
Owned,
Context,
Initializable{
using AddressUtils for address;
string constant INVALID_ADDRESS = "0501";
string constant CONTRACT_ADDRESS_NOT_SETUP = "0502";
string constant NOT_APPROVED= "0503";
string constant NOT_VALID_NFT = "0504";
string constant NOT_FOR_SALE = "0505";
string constant NOT_EHOUGH_ETHER = "0506";
string constant NEGATIVE_VALUE = "0507";
string constant NO_CHANGES_INTENDED = "0508";
string constant NOT_NFT_OWNER = "0509";
string constant INSUFICIENT_BALANCE = "0510";
string constant STILL_OWN_NFT_CONTRACT = "0511";
string constant NFT_ALREADY_MINTED = "0512";
string constant PRICE_NOT_SET = "0513";
string constant MINTING_LOCKED = "0514";
event Sent(address indexed payee, uint amount);
event RoyaltyPaid(address indexed payee, uint amount);
event SecurityWithdrawal(address indexed payee, uint amount);
StopTheWarOnDrugs public TokenContract;
/**
* @dev Mapping from token ID to its pirce.
*/
mapping(uint => uint256) internal price;
/**
* @dev Mapping from token ID to royalty address.
*/
mapping(uint => address) internal royaltyAddress;
/**
* @dev Mapping from NFT ID to boolean representing
* if it is for sale or not.
*/
mapping(uint => bool) internal forSale;
/**
* @dev contract balance
*/
uint internal contractBalance;
/**
* @dev reentrancy safe and control for minting method
*/
bool internal mintLock;
/**
* @dev Contract Constructor/Initializer
*/
function initialize() public initializer {
isOwned();
}
/**
* @dev update the address of the NFTs
* @param nmwdAddress address of NoMoreWarOnDrugs tokens
*/
function updateNMWDcontract(address nmwdAddress) external onlyOwner{
require(nmwdAddress != address(0) && nmwdAddress != address(this),INVALID_ADDRESS);
require(address(TokenContract) != nmwdAddress,NO_CHANGES_INTENDED);
TokenContract = StopTheWarOnDrugs(nmwdAddress);
}
/**
* @dev transfers ownership of the NFT contract to the owner of
* the marketplace contract. Only if the marketplace owns the NFT
*/
function getBackOwnership() external onlyOwner{
require(address(TokenContract) != address(0),CONTRACT_ADDRESS_NOT_SETUP);
TokenContract.transferOwnership(address(owner));
}
/**
* @dev Purchase _tokenId
* @param _tokenId uint token ID (painting number)
*/
function purchaseToken(uint _tokenId) external payable {
require(forSale[_tokenId], NOT_FOR_SALE);
require(_msgSender() != address(0) && _msgSender() != address(this));
require(price[_tokenId] > 0,PRICE_NOT_SET);
require(msg.value >= price[_tokenId]);
require(TokenContract.ownerOf(_tokenId) != address(0), NOT_VALID_NFT);
address tokenSeller = TokenContract.ownerOf(_tokenId);
require(TokenContract.getApproved(_tokenId) == address(this) ||
TokenContract.isApprovedForAll(tokenSeller, address(this)),
NOT_APPROVED);
forSale[_tokenId] = false;
// this is the fee of the contract per transaction: 0.8%
uint256 saleFee = (msg.value / 1000) * 8;
contractBalance += saleFee;
//calculating the net amount of the sale
uint netAmount = msg.value - saleFee;
(address royaltyReceiver, uint256 royaltyAmount) = TokenContract.royaltyInfo( _tokenId, netAmount);
//calculating the amount to pay the seller
uint256 toPaySeller = netAmount - royaltyAmount;
//paying the seller and the royalty recepient
(bool successSeller, ) =tokenSeller.call{value: toPaySeller, gas: 120000}("");
require( successSeller, "Paying seller failed");
(bool successRoyalties, ) =royaltyReceiver.call{value: royaltyAmount, gas: 120000}("");
require( successRoyalties, "Paying Royalties failed");
//transfer the NFT to the buyer
TokenContract.safeTransferFrom(tokenSeller, _msgSender(), _tokenId);
//notifying the blockchain
emit Sent(tokenSeller, toPaySeller);
emit RoyaltyPaid(royaltyReceiver, royaltyAmount);
}
/**
* @dev mint an NFT through the market place
* @param _to the address that will receive the freshly minted NFT
* @param _tokenId uint token ID (painting number)
*/
function mintThroughPurchase(address _to, uint _tokenId) external payable {
require(price[_tokenId] > 0, PRICE_NOT_SET);
require(msg.value >= price[_tokenId],NOT_EHOUGH_ETHER);
require(_msgSender() != address(0) && _msgSender() != address(this));
//avoid reentrancy. Also mintLocked before launch time.
require(!mintLock,MINTING_LOCKED);
mintLock=true;
//we extract the royalty address from the mapping
address royaltyRecipient = royaltyAddress[_tokenId];
//this is hardcoded 6.0% for all NFTs
uint royaltyValue = 600;
contractBalance += msg.value;
TokenContract.mint(_to, _tokenId, royaltyRecipient, royaltyValue);
mintLock=false;
}
/**
* @dev send / withdraw _amount to _payee
* @param _payee the address where the funds are going to go
* @param _amount the amount of Ether that will be sent
*/
function withdrawFromContract(address _payee, uint _amount) external onlyOwner {
require(_payee != address(0) && _payee != address(this));
require(contractBalance >= _amount, INSUFICIENT_BALANCE);
require(_amount > 0 && _amount <= address(this).balance, NOT_EHOUGH_ETHER);
//we check if somebody has hacked the contract, in which case we send all the funds to
//the owner of the contract
if(contractBalance != address(this).balance){
contractBalance = 0;
payable(owner).transfer(address(this).balance);
emit SecurityWithdrawal(owner, _amount);
}else{
contractBalance -= _amount;
payable(_payee).transfer(_amount);
emit Sent(_payee, _amount);
}
}
/**
* @dev Updates price for the _tokenId NFT
* @dev Throws if updating price to the same current price, or to negative
* value, or is not the owner of the NFT.
* @param _price the price in wei for the NFT
* @param _tokenId uint token ID (painting number)
*/
function setPrice(uint _price, uint _tokenId) external {
require(_price > 0, NEGATIVE_VALUE);
require(_price != price[_tokenId], NO_CHANGES_INTENDED);
//Only owner of NFT can set a price
address _address = TokenContract.ownerOf(_tokenId);
require(_address == _msgSender());
//finally, we do what we came here for.
price[_tokenId] = _price;
}
/**
* @dev Updates price for the _tokenId NFT before minting
* @dev Throws if updating price to the same current price, or to negative
* value, or if sender is not the owner of the marketplace.
* @param _price the price in wei for the NFT
* @param _tokenId uint token ID (painting number)
* @param _royaltyAddress the address that will receive the royalties.
*/
function setPriceForMinting(uint _price, uint _tokenId, address _royaltyAddress) external onlyOwner{
require(_price > 0, NEGATIVE_VALUE);
require(_price != price[_tokenId], NO_CHANGES_INTENDED);
require(_royaltyAddress != address(0) && _royaltyAddress != address(this),INVALID_ADDRESS);
//this makes sure this is only set before minting. It is impossible to change the
//royalty address once it's been minted. The price can then be only reset by the NFT owner.
require( !TokenContract.exists(_tokenId),NFT_ALREADY_MINTED);
//finally, we do what we came here for.
price[_tokenId] = _price;
royaltyAddress[_tokenId] = _royaltyAddress;
}
/**
* @dev get _tokenId price in wei
* @param _tokenId uint token ID
*/
function getPrice(uint _tokenId) external view returns (uint256){
return price[_tokenId];
}
/**
* @dev get marketplace's balance (weis)
*/
function getMarketPlaceBalance() external view returns (uint256){
return contractBalance;
}
/**
* @dev sets the token with _tokenId a boolean representing if it's for sale or not.
* @param _tokenId uint token ID
* @param _forSale is it or not for sale? (true/false)
*/
function setForSale(uint _tokenId, bool _forSale) external returns (bool){
try TokenContract.ownerOf(_tokenId) returns (address _address) {
require(_address == _msgSender(),NOT_NFT_OWNER);
}catch {
return false;
}
require(_forSale != forSale[_tokenId],NO_CHANGES_INTENDED);
forSale[_tokenId] = _forSale;
return true;
}
/**
* @dev gets the token with _tokenId forSale variable.
* @param _tokenId uint token ID
*/
function getForSale(uint _tokenId) external view returns (bool){
return forSale[_tokenId];
}
/**
* @dev Burns an NFT.
* @param _tokenId of the NFT to burn.
*/
function burn(uint256 _tokenId ) external onlyOwner {
TokenContract.burn( _tokenId);
}
/**
* @dev the receive method to avoid balance incongruence
*/
receive() external payable{
contractBalance += msg.value;
}
/**
* @dev locks/unlocks the mint method.
* @param _locked bool value to set.
*/
function setMintLock(bool _locked) external onlyOwner {
mintLock=_locked;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
contract Owned {
/**
* @dev Error constants.
*/
string public constant NOT_CURRENT_OWNER = "0101";
string public constant CANNOT_TRANSFER_TO_ZERO_ADDRESS = "0102";
/**
* @dev Current owner address.
*/
address public owner;
/**
* @dev An event which is triggered when the owner is changed.
* @param previousOwner The address of the previous owner.
* @param newOwner The address of the new owner.
*/
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
event _msg(address deliveredTo, string msg);
function isOwned() internal {
owner = msg.sender;
emit _msg(owner, "set owner" );
}
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
emit _msg(owner, "passed ownership requirement" );
_;
}
/**
* @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), CANNOT_TRANSFER_TO_ZERO_ADDRESS);
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
function getOwner() public view returns (address){
return owner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./nf-token-enumerable.sol";
import "./nf-token-metadata.sol";
import "./owned.sol";
import "./erc2981-per-token-royalties.sol";
contract StopTheWarOnDrugs is NFTokenEnumerable, NFTokenMetadata,
///Owned,
ERC2981PerTokenRoyalties {
/**
* @dev error when an NFT is attempted to be minted after the max
* supply of NFTs has been already reached.
*/
string constant MAX_TOKENS_MINTED = "0401";
/**
* @dev error when the message for an NFT is trying to be set afet
* it has been already set.
*/
string constant MESSAGE_ALREADY_SET = "0402";
/**
* @dev The message doesn't comply with the size restrictions
*/
string constant NOT_VALID_MSG = "0403";
/**
* @dev Can't pass 0 as value for the argument
*/
string constant ZERO_VALUE = "0404";
/**
* @dev The maximum amount of NFTs that can be minted in this collection
*/
uint16 constant MAX_TOKENS = 904;
/**
* @dev Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
* which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
*/
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
/**
* @dev Mapping from NFT ID to message.
*/
mapping (uint256 => string) private idToMsg;
constructor(string memory _name, string memory _symbol){
isOwned();
nftName = _name;
nftSymbol = _symbol;
}
/**
* @dev Mints a new NFT.
* @notice an approveForAll is given to the owner of the contract.
* This is due to the fact that the marketplae of this project will
* own this contract. Therefore, the NFTs will be transactable in
* the marketplace by default without any extra step from the user.
* @param _to The address that will own the minted NFT.
* @param _tokenId of the NFT to be minted by the msg.sender.
* @param royaltyRecipient the address that will be entitled for the royalties.
* @param royaltyValue the percentage (from 0 - 10000) of the royalties
* @notice royaltyValue is amplified 100 times to be able to write a percentage
* with 2 decimals of precision. Therefore, 1 => 0.01%; 100 => 1%; 10000 => 100%
* @notice the URI is build from the tokenId since it is the SHA2-256 of the
* URI content in IPFS.
*/
function mint(address _to, uint256 _tokenId,
address royaltyRecipient, uint256 royaltyValue)
external onlyOwner
{
_mint(_to, _tokenId);
//uri setup
string memory _uri = getURI(_tokenId);
idToUri[_tokenId] = _uri;
//royalties setup
if (royaltyValue > 0) {
_setTokenRoyalty(_tokenId, royaltyRecipient, royaltyValue);
}
//approve marketplace
if(!ownerToOperators[_to][owner]){
ownerToOperators[_to][owner] = true;
}
}
/**
* @dev Mints a new NFT.
* @param _to The address that will own the minted NFT.
* @param _tokenId of the NFT to be minted by the msg.sender.
*/
function _mint( address _to, uint256 _tokenId ) internal override (NFTokenEnumerable, NFToken){
require( tokens.length < MAX_TOKENS, MAX_TOKENS_MINTED );
super._mint(_to, _tokenId);
}
/**
* @dev Assignes a new NFT to an address.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _to Address to wich we want to add the NFT.
* @param _tokenId Which NFT we want to add.
*/
function _addNFToken( address _to, uint256 _tokenId ) internal override (NFTokenEnumerable, NFToken){
super._addNFToken(_to, _tokenId);
}
function addNFToken(address _to, uint256 _tokenId) internal {
_addNFToken(_to, _tokenId);
}
/**
* @dev Burns a NFT.
* @notice This is an internal function which should be called from user-implemented external
* burn function. Its purpose is to show and properly initialize data structures when using this
* implementation. Also, note that this burn implementation allows the minter to re-mint a burned
* NFT.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn( uint256 _tokenId ) internal override (NFTokenEnumerable, NFTokenMetadata) {
super._burn(_tokenId);
}
function burn(uint256 _tokenId ) public onlyOwner {
//clearing the uri
idToUri[_tokenId] = "";
//clearing the royalties
_setTokenRoyalty(_tokenId, address(0), 0);
//burning the token for good
_burn( _tokenId);
}
/**
* @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable
* extension to remove double storage(gas optimization) of owner nft count.
* @param _owner Address for whom to query the count.
* @return Number of _owner NFTs.
*/
function _getOwnerNFTCount( address _owner ) internal override(NFTokenEnumerable, NFToken) view returns (uint256) {
return super._getOwnerNFTCount(_owner);
}
function getOwnerNFTCount( address _owner ) public view returns (uint256) {
return _getOwnerNFTCount(_owner);
}
/**
* @dev Removes a NFT from an address.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _from Address from wich we want to remove the NFT.
* @param _tokenId Which NFT we want to remove.
*/
function _removeNFToken(
address _from,
uint256 _tokenId
)
internal
override (NFTokenEnumerable, NFToken)
{
super._removeNFToken(_from, _tokenId);
}
function removeNFToken(address _from, uint256 _tokenId) internal {
_removeNFToken(_from, _tokenId);
}
/**
* @dev A custom message given for the first NFT buyer.
* @param _tokenId Id for which we want the message.
* @return Message of _tokenId.
*/
function tokenMessage(
uint256 _tokenId
)
external
view
validNFToken(_tokenId)
returns (string memory)
{
return idToMsg[_tokenId];
}
/**
* @dev Sets a custom message for the NFT with _tokenId.
* @notice only the owner of the NFT can do this. Not even approved or
* operators can execute this function.
* @param _tokenId Id for which we want the message.
* @param _msg the custom message.
*/
function setTokenMessage(
uint256 _tokenId,
string memory _msg
)
external
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_msgSender() == tokenOwner, NOT_OWNER);
require(bytes(idToMsg[_tokenId]).length == 0, MESSAGE_ALREADY_SET);
bool valid_msg = validateMsg(_msg);
require(valid_msg, NOT_VALID_MSG);
idToMsg[_tokenId] = _msg;
}
/**
* @dev Check if the message string has a valid length
* @param _msg the custom message.
*/
function validateMsg(string memory _msg) public pure returns (bool){
bytes memory b = bytes(_msg);
if(b.length < 1) return false;
if(b.length > 300) return false; // Cannot be longer than 300 characters
return true;
}
/**
* @dev returns the list of NFTs owned by certain address.
* @param _address Id for which we want the message.
*/
function getNFTsByAddress(
address _address
)
view external returns (uint256[] memory)
{
return ownerToIds[_address];
}
/**
* @dev Builds and return the URL string from the tokenId.
* @notice the tokenId is the SHA2-256 of the URI content in IPFS.
* This ensures the complete authenticity of the token minted. The URL is
* therefore an IPFS URL which follows the pattern:
* ipfs://<CID>
* And the CID can be constructed as follows:
* CID = F01701220<ID>
* F signals that the CID is in hexadecimal format. 01 means CIDv1. 70 signals
* dag-pg link-data coding used. 12 references the hashing algorith SHA2-256.
* 20 is the length in bytes of the hash. In decimal, 32 bytes as specified
* in the SHA2-256 protocol. Finally, <ID> is the tokenId (the hash).
* @param _tokenId of the NFT (the SHA2-256 of the URI content).
*/
function getURI(uint _tokenId) internal pure returns(string memory){
string memory _hex = uintToHexStr(_tokenId);
string memory prefix = "ipfs://F01701220";
string memory result = string(abi.encodePacked(prefix,_hex ));
return result;
}
/**
* @dev Converts a uint into a hex string of 64 characters. Throws if 0 is passed.
* @notice that the returned string doesn't prepend the usual "0x".
* @param _uint number to convert to string.
*/
function uintToHexStr(uint _uint) internal pure returns (string memory) {
require(_uint != 0, ZERO_VALUE);
bytes memory byteStr = new bytes(64);
for (uint j = 0; j < 64 ;j++){
uint curr = (_uint & 15); //mask that allows us to filter only the last 4 bits (last character)
byteStr[63-j] = curr > 9 ? bytes1( uint8(55) + uint8(curr) ) :
bytes1( uint8(48) + uint8(curr) ); // 55 = 65 - 10
_uint = _uint >> 4;
}
return string(byteStr);
}
/**
* @dev Destroys the contract
* @notice that, due to the danger that the call of this contract poses, it is required
* to pass a specific integer value to effectively call this method.
* @param security_value number to pass security restriction (192837).
*/
function seflDestruct(uint security_value) external onlyOwner {
require(security_value == 192837); //this is just to make sure that this method was not called by accident
selfdestruct(payable(owner));
}
/**
* @dev returns boolean representing the existance of an NFT
* @param _tokenId of the NFT to look up.
*/
function exists(uint _tokenId) external view returns (bool) {
if( idToOwner[_tokenId] == address(0)){
return false;
}else{
return true;
}
}
}
// 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 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 payable(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.8.0;
/**
* @dev Utility library of inline functions on addresses.
* @notice Based on:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol
* Requires EIP-1052.
*/
library AddressUtils
{
/**
* @dev Returns whether the target address is a contract.
* @param _addr Address to check.
* @return addressCheck True if _addr is a contract, false if not.
*/
function isContract(
address _addr
)
internal
view
returns (bool addressCheck)
{
// 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;
assembly { codehash := extcodehash(_addr) } // solhint-disable-line
addressCheck = (codehash != 0x0 && codehash != accountHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./nf-token.sol";
import "./erc721-enumerable.sol";
/**
* @dev Optional enumeration implementation for ERC-721 non-fungible token standard.
*/
contract NFTokenEnumerable is NFToken, ERC721Enumerable {
/**
* @dev List of revert message codes. Implementing dApp should handle showing the correct message.
* Based on 0xcert framework error codes.
*/
string constant INVALID_INDEX = "0201";
/**
* @dev Array of all NFT IDs.
*/
uint256[] internal tokens;
/**
* @dev Mapping from token ID to its index in global tokens array.
*/
mapping(uint256 => uint256) internal idToIndex;
/**
* @dev Mapping from owner to list of owned NFT IDs.
*/
mapping(address => uint256[]) internal ownerToIds;
/**
* @dev Mapping from NFT ID to its index in the owner tokens list.
*/
mapping(uint256 => uint256) internal idToOwnerIndex;
/**
* @dev Contract constructor.
*/
constructor()
{
supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable
}
/**
* @dev Returns the count of all existing NFTokens.
* @return Total supply of NFTs.
*/
function totalSupply()
external
override
view
returns (uint256)
{
return tokens.length;
}
/**
* @dev Returns NFT ID by its index.
* @param _index A counter less than `totalSupply()`.
* @return Token id.
*/
function tokenByIndex(
uint256 _index
)
external
override
view
returns (uint256)
{
require(_index < tokens.length, INVALID_INDEX);
return tokens[_index];
}
/**
* @dev returns the n-th NFT ID from a list of owner's tokens.
* @param _owner Token owner's address.
* @param _index Index number representing n-th token in owner's list of tokens.
* @return Token id.
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
external
override
view
returns (uint256)
{
require(_index < ownerToIds[_owner].length, INVALID_INDEX);
return ownerToIds[_owner][_index];
}
/**
* @dev Mints a new NFT.
* @notice This is an internal function which should be called from user-implemented external
* mint function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _to The address that will own the minted NFT.
* @param _tokenId of the NFT to be minted by the msg.sender.
*/
function _mint(
address _to,
uint256 _tokenId
)
internal
override
virtual
{
super._mint(_to, _tokenId);
tokens.push(_tokenId);
idToIndex[_tokenId] = tokens.length - 1;
}
/**
* @dev Burns a NFT.
* @notice This is an internal function which should be called from user-implemented external
* burn function. Its purpose is to show and properly initialize data structures when using this
* implementation. Also, note that this burn implementation allows the minter to re-mint a burned
* NFT.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn(
uint256 _tokenId
)
internal
override
virtual
{
super._burn(_tokenId);
uint256 tokenIndex = idToIndex[_tokenId];
uint256 lastTokenIndex = tokens.length - 1;
uint256 lastToken = tokens[lastTokenIndex];
tokens[tokenIndex] = lastToken;
tokens.pop();
// This wastes gas if you are burning the last token but saves a little gas if you are not.
idToIndex[lastToken] = tokenIndex;
idToIndex[_tokenId] = 0;
}
/**
* @dev Removes a NFT from an address.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _from Address from wich we want to remove the NFT.
* @param _tokenId Which NFT we want to remove.
*/
function _removeNFToken(
address _from,
uint256 _tokenId
)
internal
override
virtual
{
require(idToOwner[_tokenId] == _from, NOT_OWNER);
delete idToOwner[_tokenId];
uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId];
uint256 lastTokenIndex = ownerToIds[_from].length - 1;
if (lastTokenIndex != tokenToRemoveIndex)
{
uint256 lastToken = ownerToIds[_from][lastTokenIndex];
ownerToIds[_from][tokenToRemoveIndex] = lastToken;
idToOwnerIndex[lastToken] = tokenToRemoveIndex;
}
ownerToIds[_from].pop();
}
/**
* @dev Assignes a new NFT to an address.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _to Address to wich we want to add the NFT.
* @param _tokenId Which NFT we want to add.
*/
function _addNFToken(
address _to,
uint256 _tokenId
)
internal
override
virtual
{
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
idToOwner[_tokenId] = _to;
ownerToIds[_to].push(_tokenId);
idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1;
}
/**
* @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable
* extension to remove double storage(gas optimization) of owner nft count.
* @param _owner Address for whom to query the count.
* @return Number of _owner NFTs.
*/
function _getOwnerNFTCount(
address _owner
)
internal
override
virtual
view
returns (uint256)
{
return ownerToIds[_owner].length;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./nf-token.sol";
import "./erc721-metadata.sol";
/**
* @dev Optional metadata implementation for ERC-721 non-fungible token standard.
*/
contract NFTokenMetadata is
NFToken,
ERC721Metadata
{
/**
* @dev A descriptive name for a collection of NFTs.
*/
string internal nftName;
/**
* @dev An abbreviated name for NFTokens.
*/
string internal nftSymbol;
/**
* @dev Mapping from NFT ID to metadata uri.
*/
mapping (uint256 => string) internal idToUri;
/**
* @dev Contract constructor.
* @notice When implementing this contract don't forget to set nftName and nftSymbol.
*/
constructor()
{
supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata
}
/**
* @dev Returns a descriptive name for a collection of NFTokens.
* @return _name Representing name.
*/
function name()
external
override
view
returns (string memory _name)
{
_name = nftName;
}
/**
* @dev Returns an abbreviated name for NFTokens.
* @return _symbol Representing symbol.
*/
function symbol()
external
override
view
returns (string memory _symbol)
{
_symbol = nftSymbol;
}
/**
* @dev A distinct URI (RFC 3986) for a given NFT.
* @param _tokenId Id for which we want uri.
* @return URI of _tokenId.
*/
function tokenURI(
uint256 _tokenId
)
external
override
view
validNFToken(_tokenId)
returns (string memory)
{
return idToUri[_tokenId];
}
/**
* @dev Burns a NFT.
* @notice This is an internal function which should be called from user-implemented external
* burn function. Its purpose is to show and properly initialize data structures when using this
* implementation. Also, note that this burn implementation allows the minter to re-mint a burned
* NFT.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn(
uint256 _tokenId
)
internal
override
virtual
{
super._burn(_tokenId);
if (bytes(idToUri[_tokenId]).length != 0)
{
delete idToUri[_tokenId];
}
}
/**
* @dev Set a distinct URI (RFC 3986) for a given NFT ID.
* @notice This is an internal function which should be called from user-implemented external
* function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _tokenId Id for which we want URI.
* @param _uri String representing RFC 3986 URI.
*/
function _setTokenUri(
uint256 _tokenId,
string memory _uri
)
internal
validNFToken(_tokenId)
{
idToUri[_tokenId] = _uri;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import './ierc2981-royalties.sol';
import "./supports-interface.sol";
/// @dev This is a contract used to add ERC2981 support to ERC721 and 1155
contract ERC2981PerTokenRoyalties is IERC2981Royalties, SupportsInterface {
/**
* @dev This is where the info about the royalty resides
* @dev recipient is the address where the royalties should be sent to.
* @dev value is the percentage of the sale value that will be sent as royalty.
* @notice "value" will be expressed as an unsigned integer between 0 and 1000.
* This means that 10000 = 100%, and 1 = 0.01%
*/
struct Royalty {
address recipient;
uint256 value;
}
/**
* @dev the data structure where the NFT id points to the Royalty struct with the
* corresponding royalty info.
*/
mapping(uint256 => Royalty) internal idToRoyalties;
constructor(){
supportedInterfaces[0x2a55205a] = true; // ERC2981
}
/**
* @dev Sets token royalties
* @param id the token id fir which we register the royalties
* @param recipient recipient of the royalties
* @param value percentage (using 2 decimals - 10000 = 100, 0 = 0)
*/
function _setTokenRoyalty(
uint256 id,
address recipient,
uint256 value
) internal {
require(value <= 10000, 'ERC2981Royalties: Too high');
idToRoyalties[id] = Royalty(recipient, value);
}
/// @inheritdoc IERC2981Royalties
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
Royalty memory royalty = idToRoyalties[_tokenId];
return (royalty.recipient, (_salePrice * royalty.value) / 10000);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./erc721.sol";
import "./erc721-token-receiver.sol";
import "./supports-interface.sol";
import "./address-utils.sol";
import "./context.sol";
import "./owned.sol";
/**
* @dev Implementation of ERC-721 non-fungible token standard.
*/
contract NFToken is
ERC721,
Context,
SupportsInterface,
Owned
{
using AddressUtils for address;
/**
* @dev List of revert message codes. Implementing dApp should handle showing the correct message.
* Based on 0xcert framework error codes.
*/
string constant ZERO_ADDRESS = "0301";
string constant NOT_VALID_NFT = "0302";
string constant NOT_OWNER_OR_OPERATOR = "0303";
string constant NOT_OWNER_APPROVED_OR_OPERATOR = "0304";
string constant NOT_ABLE_TO_RECEIVE_NFT = "0305";
string constant NFT_ALREADY_EXISTS = "0306";
string constant NOT_OWNER = "0307";
string constant IS_OWNER = "0308";
/**
* @dev Magic value of a smart contract that can recieve NFT.
* Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")).
*/
bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02;
/**
* @dev A mapping from NFT ID to the address that owns it.
*/
mapping (uint256 => address) internal idToOwner;
/**
* @dev Mapping from NFT ID to approved address.
*/
mapping (uint256 => address) internal idToApproval;
/**
* @dev Mapping from owner address to count of his tokens.
*/
mapping (address => uint256) private ownerToNFTokenCount;
/**
* @dev Mapping from owner address to mapping of operator addresses.
*/
mapping (address => mapping (address => bool)) internal ownerToOperators;
/**
* @dev Guarantees that the_msgSender() is an owner or operator of the given NFT.
* @param _tokenId ID of the NFT to validate.
*/
modifier canOperate(
uint256 _tokenId
)
{
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner ==_msgSender() || ownerToOperators[tokenOwner][msg.sender],
NOT_OWNER_OR_OPERATOR
);
_;
}
/**
* @dev Guarantees that the_msgSender() is allowed to transfer NFT.
* @param _tokenId ID of the NFT to transfer.
*/
modifier canTransfer(
uint256 _tokenId
)
{
address tokenOwner = idToOwner[_tokenId];
require(
tokenOwner ==_msgSender()
|| idToApproval[_tokenId] ==_msgSender()
|| ownerToOperators[tokenOwner][msg.sender],
NOT_OWNER_APPROVED_OR_OPERATOR
);
_;
}
/**
* @dev Guarantees that _tokenId is a valid Token.
* @param _tokenId ID of the NFT to validate.
*/
modifier validNFToken(
uint256 _tokenId
)
{
require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT);
_;
}
/**
* @dev Contract constructor.
*/
constructor()
{
supportedInterfaces[0x80ac58cd] = true; // ERC721
}
/**
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external
override
{
_safeTransferFrom(_from, _to, _tokenId, _data);
}
/**
* @dev Transfers the ownership of an NFT from one address to another address. This function can
* be changed to payable.
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to ""
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
override
{
_safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable.
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they maybe be permanently lost.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
override
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, NOT_OWNER);
require(_to != address(0), ZERO_ADDRESS);
_transfer(_to, _tokenId);
}
/**
* @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable.
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved Address to be approved for the given NFT ID.
* @param _tokenId ID of the token to be approved.
*/
function approve(
address _approved,
uint256 _tokenId
)
external
override
canOperate(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(_approved != tokenOwner, IS_OWNER);
idToApproval[_tokenId] = _approved;
emit Approval(tokenOwner, _approved, _tokenId);
}
/**
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @notice This works even if sender doesn't own any tokens at the time.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(
address _operator,
bool _approved
)
external
override
{
ownerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
* @return Balance of _owner.
*/
function balanceOf(
address _owner
)
external
override
view
returns (uint256)
{
require(_owner != address(0), ZERO_ADDRESS);
return _getOwnerNFTCount(_owner);
}
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered
* invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
* @return _owner Address of _tokenId owner.
*/
function ownerOf(
uint256 _tokenId
)
external
override
view
returns (address _owner)
{
_owner = idToOwner[_tokenId];
require(_owner != address(0), NOT_VALID_NFT);
}
/**
* @dev Get the approved address for a single NFT.
* @notice Throws if `_tokenId` is not a valid NFT.
* @param _tokenId ID of the NFT to query the approval of.
* @return Address that _tokenId is approved for.
*/
function getApproved(
uint256 _tokenId
)
external
override
view
validNFToken(_tokenId)
returns (address)
{
return idToApproval[_tokenId];
}
/**
* @dev Checks if `_operator` is an approved operator for `_owner`.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
* @return True if approved for all, false otherwise.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
override
view
returns (bool)
{
return ownerToOperators[_owner][_operator];
}
/**
* @dev Actually preforms the transfer.
* @notice Does NO checks.
* @param _to Address of a new owner.
* @param _tokenId The NFT that is being transferred.
*/
function _transfer(
address _to,
uint256 _tokenId
)
internal
{
address from = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(from, _tokenId);
_addNFToken(_to, _tokenId);
//Native marketplace (owner) will always be an authorized operator.
if(!ownerToOperators[_to][owner]){
ownerToOperators[_to][owner] = true;
}
emit Transfer(from, _to, _tokenId);
}
/**
* @dev Mints a new NFT.
* @notice This is an internal function which should be called from user-implemented external
* mint function. Its purpose is to show and properly initialize data structures when using this
* implementation.
* @param _to The address that will own the minted NFT.
* @param _tokenId of the NFT to be minted by the_msgSender().
*/
function _mint(
address _to,
uint256 _tokenId
)
internal
virtual
{
require(_to != address(0), ZERO_ADDRESS);
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
_addNFToken(_to, _tokenId);
if (_to.isContract())
{
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, address(0), _tokenId, "");
require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT);
}
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Burns a NFT.
* @notice This is an internal function which should be called from user-implemented external burn
* function. Its purpose is to show and properly initialize data structures when using this
* implementation. Also, note that this burn implementation allows the minter to re-mint a burned
* NFT.
* @param _tokenId ID of the NFT to be burned.
*/
function _burn(
uint256 _tokenId
)
internal
virtual
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
_clearApproval(_tokenId);
_removeNFToken(tokenOwner, _tokenId);
emit Transfer(tokenOwner, address(0), _tokenId);
}
/**
* @dev Removes a NFT from owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _from Address from wich we want to remove the NFT.
* @param _tokenId Which NFT we want to remove.
*/
function _removeNFToken(
address _from,
uint256 _tokenId
)
internal
virtual
{
require(idToOwner[_tokenId] == _from, NOT_OWNER);
ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1;
delete idToOwner[_tokenId];
}
/**
* @dev Assignes a new NFT to owner.
* @notice Use and override this function with caution. Wrong usage can have serious consequences.
* @param _to Address to wich we want to add the NFT.
* @param _tokenId Which NFT we want to add.
*/
function _addNFToken(
address _to,
uint256 _tokenId
)
internal
virtual
{
require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS);
idToOwner[_tokenId] = _to;
ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to] + 1;
}
/**
* @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable
* extension to remove double storage (gas optimization) of owner nft count.
* @param _owner Address for whom to query the count.
* @return Number of _owner NFTs.
*/
function _getOwnerNFTCount(
address _owner
)
internal
virtual
view
returns (uint256)
{
return ownerToNFTokenCount[_owner];
}
/**
* @dev Actually perform the safeTransferFrom.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function _safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
private
canTransfer(_tokenId)
validNFToken(_tokenId)
{
address tokenOwner = idToOwner[_tokenId];
require(tokenOwner == _from, NOT_OWNER);
require(_to != address(0), ZERO_ADDRESS);
_transfer(_to, _tokenId);
if (_to.isContract())
{
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT);
}
}
/**
* @dev Clears the current approval of a given NFT ID.
* @param _tokenId ID of the NFT to be transferred.
*/
function _clearApproval(
uint256 _tokenId
)
private
{
if (idToApproval[_tokenId] != address(0))
{
delete idToApproval[_tokenId];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev Optional enumeration extension for ERC-721 non-fungible token standard.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721Enumerable
{
/**
* @dev Returns a count of valid NFTs tracked by this contract, where each one of them has an
* assigned and queryable owner not equal to the zero address.
* @return Total supply of NFTs.
*/
function totalSupply()
external
view
returns (uint256);
/**
* @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified.
* @param _index A counter less than `totalSupply()`.
* @return Token id.
*/
function tokenByIndex(
uint256 _index
)
external
view
returns (uint256);
/**
* @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is
* not specified. It throws if `_index` >= `balanceOf(_owner)` or if `_owner` is the zero address,
* representing invalid NFTs.
* @param _owner An address where we are interested in NFTs owned by them.
* @param _index A counter less than `balanceOf(_owner)`.
* @return Token id.
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
external
view
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev ERC-721 non-fungible token standard.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721
{
/**
* @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are
* created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any
* number of NFTs may be created and assigned without emitting Transfer. At the time of any
* transfer, the approved address for that NFT (if any) is reset to none.
*/
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
/**
* @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero
* address indicates there is no approved address. When a Transfer event emits, this also
* indicates that the approved address for that NFT (if any) is reset to none.
*/
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
/**
* @dev This emits when an operator is enabled or disabled for an owner. The operator can manage
* all NFTs of the owner.
*/
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the
* approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is
* the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this
* function checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
* @param _data Additional data with no specified format, sent in call to `_to`.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes calldata _data
)
external;
/**
* @dev Transfers the ownership of an NFT from one address to another address.
* @notice This works identically to the other function with an extra data parameter, except this
* function just sets data to ""
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/**
* @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved
* address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero
* address. Throws if `_tokenId` is not a valid NFT.
* @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else
* they mayb be permanently lost.
* @param _from The current owner of the NFT.
* @param _to The new owner.
* @param _tokenId The NFT to transfer.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external;
/**
* @dev Set or reaffirm the approved address for an NFT.
* @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is
* the current NFT owner, or an authorized operator of the current owner.
* @param _approved The new approved NFT controller.
* @param _tokenId The NFT to approve.
*/
function approve(
address _approved,
uint256 _tokenId
)
external;
/**
* @dev Enables or disables approval for a third party ("operator") to manage all of
* `msg.sender`'s assets. It also emits the ApprovalForAll event.
* @notice The contract MUST allow multiple operators per owner.
* @param _operator Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval.
*/
function setApprovalForAll(
address _operator,
bool _approved
)
external;
/**
* @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
* considered invalid, and this function throws for queries about the zero address.
* @param _owner Address for whom to query the balance.
* @return Balance of _owner.
*/
function balanceOf(
address _owner
)
external
view
returns (uint256);
/**
* @dev Returns the address of the owner of the NFT. NFTs assigned to zero address are considered
* invalid, and queries about them do throw.
* @param _tokenId The identifier for an NFT.
* @return Address of _tokenId owner.
*/
function ownerOf(
uint256 _tokenId
)
external
view
returns (address);
/**
* @dev Get the approved address for a single NFT.
* @notice Throws if `_tokenId` is not a valid NFT.
* @param _tokenId The NFT to find the approved address for.
* @return Address that _tokenId is approved for.
*/
function getApproved(
uint256 _tokenId
)
external
view
returns (address);
/**
* @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise.
* @param _owner The address that owns the NFTs.
* @param _operator The address that acts on behalf of the owner.
* @return True if approved for all, false otherwise.
*/
function isApprovedForAll(
address _owner,
address _operator
)
external
view
returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev ERC-721 interface for accepting safe transfers.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721TokenReceiver
{
/**
* @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the
* recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return
* of other than the magic value MUST result in the transaction being reverted.
* Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing.
* @notice The contract address is always the message sender. A wallet/broker/auction application
* MUST implement the wallet interface if it will accept safe transfers.
* @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 Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "./erc165.sol";
/**
* @dev Implementation of standard for detect smart contract interfaces.
*/
contract SupportsInterface is
ERC165
{
/**
* @dev Mapping of supported intefraces. You must not set element 0xffffffff to true.
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev Contract constructor.
*/
constructor()
{
supportedInterfaces[0x01ffc9a7] = true; // ERC165
}
/**
* @dev Function to check which interfaces are suported by this contract.
* @param _interfaceID Id of the interface.
* @return True if _interfaceID is supported, false otherwise.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
override
view
returns (bool)
{
return supportedInterfaces[_interfaceID];
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev A standard for detecting smart contract interfaces.
* See: https://eips.ethereum.org/EIPS/eip-165.
*/
interface ERC165
{
/**
* @dev Checks if the smart contract includes a specific interface.
* This function uses less than 30,000 gas.
* @param _interfaceID The interface identifier, as specified in ERC-165.
* @return True if _interfaceID is supported, false otherwise.
*/
function supportsInterface(
bytes4 _interfaceID
)
external
view
returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/**
* @dev Optional metadata extension for ERC-721 non-fungible token standard.
* See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md.
*/
interface ERC721Metadata
{
/**
* @dev Returns a descriptive name for a collection of NFTs in this contract.
* @return _name Representing name.
*/
function name()
external
view
returns (string memory _name);
/**
* @dev Returns a abbreviated name for a collection of NFTs in this contract.
* @return _symbol Representing symbol.
*/
function symbol()
external
view
returns (string memory _symbol);
/**
* @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if
* `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file
* that conforms to the "ERC721 Metadata JSON Schema".
* @return URI of _tokenId.
*/
function tokenURI(uint256 _tokenId)
external
view
returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title IERC2981Royalties
/// @dev Interface for the ERC2981 - Token Royalty standard
interface IERC2981Royalties {
/// @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 value sale price
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
} | * @dev Purchase _tokenId @param _tokenId uint token ID (painting number)/ this is the fee of the contract per transaction: 0.8%calculating the net amount of the salecalculating the amount to pay the sellerpaying the seller and the royalty recepienttransfer the NFT to the buyernotifying the blockchain | function purchaseToken(uint _tokenId) external payable {
require(forSale[_tokenId], NOT_FOR_SALE);
require(_msgSender() != address(0) && _msgSender() != address(this));
require(price[_tokenId] > 0,PRICE_NOT_SET);
require(msg.value >= price[_tokenId]);
require(TokenContract.ownerOf(_tokenId) != address(0), NOT_VALID_NFT);
address tokenSeller = TokenContract.ownerOf(_tokenId);
require(TokenContract.getApproved(_tokenId) == address(this) ||
TokenContract.isApprovedForAll(tokenSeller, address(this)),
NOT_APPROVED);
forSale[_tokenId] = false;
uint256 saleFee = (msg.value / 1000) * 8;
contractBalance += saleFee;
uint netAmount = msg.value - saleFee;
(address royaltyReceiver, uint256 royaltyAmount) = TokenContract.royaltyInfo( _tokenId, netAmount);
uint256 toPaySeller = netAmount - royaltyAmount;
require( successSeller, "Paying seller failed");
require( successRoyalties, "Paying Royalties failed");
TokenContract.safeTransferFrom(tokenSeller, _msgSender(), _tokenId);
emit Sent(tokenSeller, toPaySeller);
emit RoyaltyPaid(royaltyReceiver, royaltyAmount);
}
| 5,804,195 | [
1,
23164,
389,
2316,
548,
225,
389,
2316,
548,
2254,
1147,
1599,
261,
84,
1598,
310,
1300,
13176,
333,
353,
326,
14036,
434,
326,
6835,
1534,
2492,
30,
374,
18,
28,
9,
12780,
1776,
326,
2901,
3844,
434,
326,
12814,
557,
287,
1934,
1776,
326,
3844,
358,
8843,
326,
29804,
10239,
310,
326,
29804,
471,
326,
721,
93,
15006,
2637,
84,
1979,
13866,
326,
423,
4464,
358,
326,
27037,
12336,
310,
326,
16766,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
23701,
1345,
12,
11890,
389,
2316,
548,
13,
3903,
8843,
429,
225,
288,
203,
3639,
2583,
12,
1884,
30746,
63,
67,
2316,
548,
6487,
4269,
67,
7473,
67,
5233,
900,
1769,
203,
3639,
2583,
24899,
3576,
12021,
1435,
480,
1758,
12,
20,
13,
597,
389,
3576,
12021,
1435,
480,
1758,
12,
2211,
10019,
203,
3639,
2583,
12,
8694,
63,
67,
2316,
548,
65,
405,
374,
16,
7698,
1441,
67,
4400,
67,
4043,
1769,
203,
3639,
2583,
12,
3576,
18,
1132,
1545,
6205,
63,
67,
2316,
548,
19226,
203,
3639,
2583,
12,
1345,
8924,
18,
8443,
951,
24899,
2316,
548,
13,
480,
1758,
12,
20,
3631,
4269,
67,
5063,
67,
50,
4464,
1769,
203,
203,
3639,
1758,
1147,
22050,
273,
3155,
8924,
18,
8443,
951,
24899,
2316,
548,
1769,
203,
3639,
2583,
12,
1345,
8924,
18,
588,
31639,
24899,
2316,
548,
13,
422,
1758,
12,
2211,
13,
747,
7010,
7734,
3155,
8924,
18,
291,
31639,
1290,
1595,
12,
2316,
22050,
16,
1758,
12,
2211,
13,
3631,
7010,
7734,
4269,
67,
2203,
3373,
12135,
1769,
203,
203,
3639,
364,
30746,
63,
67,
2316,
548,
65,
273,
629,
31,
203,
203,
203,
3639,
2254,
5034,
272,
5349,
14667,
273,
261,
3576,
18,
1132,
342,
4336,
13,
380,
1725,
31,
203,
3639,
6835,
13937,
1011,
272,
5349,
14667,
31,
203,
203,
3639,
2254,
2901,
6275,
273,
1234,
18,
1132,
300,
272,
5349,
14667,
31,
203,
203,
3639,
261,
2867,
721,
93,
15006,
12952,
16,
2254,
5034,
721,
93,
15006,
6275,
13,
273,
3155,
8924,
18,
3800,
2
] |
pragma solidity ^0.4.26;
import "./Ownable.sol";
import "./Validatable.sol";
import "./SafeMath.sol";
import "./Oracle.sol";
/**
@dev Controller for Long/Short options
on the Ethereum blockchain.
@author Convoluted Labs
*/
contract LongShortController is Ownable, Validatable {
// Use Zeppelin's SafeMath library for calculations
using SafeMath for uint256;
/**
@dev Position struct
*/
struct Position {
bool isLong;
bytes32 ownerSignature;
address paymentAddress;
uint256 balance;
}
/**
@dev Activated LongShort struct
*/
struct LongShort {
bytes7 currencyPair;
uint256 startingPrice;
uint closingDate;
uint8 leverage;
}
/// List of active closing dates
uint[] public activeClosingDates;
mapping(uint => bytes32[]) private longShortHashes;
mapping(bytes32 => LongShort) private longShorts;
mapping(bytes32 => Position[]) private positions;
/// Queued rewards
address[] private rewardableAddresses;
mapping(address => uint256) private rewards;
/// Price oracle contract and address
Oracle public oracle;
address public oracleAddress;
/**
@dev Links Vanilla's oracle to the contract
@param _oracleAddress The address of the deployed oracle contract
*/
function linkOracle(address _oracleAddress) public onlyOwner {
oracleAddress = _oracleAddress;
oracle = Oracle(oracleAddress);
}
/**
@dev LongShort opener function. Can only be called by the owner.
@param parameterHash Hash of the parameters, used in creating the unique LongShortHash
@param currencyPair A 7-character representation of a currency pair
@param duration seconds to closing date from block.timestamp
@param leverage A modifier which defines the rewards and the allowed price jump
@param ownerSignatures A list of bytes32 signatures for position owners
@param paymentAddresses A list of addresses to be rewarded
@param balances A list of original bet amounts
@param isLongs A list of position types {true: "LONG", false: "SHORT"}
*/
function openLongShort(bytes32 parameterHash, bytes7 currencyPair, uint duration, uint8 leverage, bytes32[] ownerSignatures, address[] paymentAddresses, uint256[] balances, bool[] isLongs) public payable onlyOwner {
/// Input validation
require(ownerSignatures.length == paymentAddresses.length, "Signature and address amounts don't match!");
require(paymentAddresses.length == balances.length, "Address and balance amounts don't match!");
require(balances.length == isLongs.length, "Balance and position type amounts don't match!");
requireZeroSum(isLongs, balances);
validateLeverage(leverage);
/// Get latest price for the currency pair from the Oracle
uint256 startingPrice = oracle.price(currencyPair);
/// Require that the Oracle has price information of the currency pair
require(startingPrice > 0, "Oracle doesn't have a price for this currency pair!");
/// Make a unique identifier for the LongShort in question
bytes32 longShortHash = keccak256(abi.encodePacked(this, parameterHash, block.timestamp));
/// Add the duration to the current block timestamp to create a closing date
uint closingDate = block.timestamp.add(duration);
/// Add positions to the LongShort
for (uint i = 0; i < isLongs.length; i++) {
positions[longShortHash].push(Position(isLongs[i], ownerSignatures[i], paymentAddresses[i], balances[i]));
}
/// Add knowledge of the new LongShort to the blockchain
activeClosingDates.push(closingDate);
longShortHashes[closingDate].push(longShortHash);
longShorts[longShortHash] = LongShort(currencyPair, startingPrice, closingDate, leverage);
}
/**
@dev Calculates reward for a single position with given parameters
@param isLong {true: "LONG", false: "SHORT"}
@param balance the balance to calculate a reward for
@param leverage leverage of the LongShort
@param startingPrice price fetched from the Oracle on creation
@param closingPrice price fetched from the Oracle when this function was called
@return {
"reward": "Reward that is added to a payment pool"
}
*/
function calculateReward(bool isLong, uint256 balance, uint8 leverage, uint256 startingPrice, uint256 closingPrice) public pure returns (uint256 reward) {
uint256 priceDiff = startingPrice > closingPrice ? startingPrice.sub(closingPrice) : closingPrice.sub(startingPrice);
uint256 diffPercentage = priceDiff.mul(10000).mul(leverage).div(startingPrice);
uint256 balanceDiff = balance.mul(diffPercentage).div(10000);
if (balanceDiff > balance) {
balanceDiff = balance;
}
if (startingPrice > closingPrice && isLong || startingPrice <= closingPrice && !isLong) {
reward = balance.sub(balanceDiff);
} else {
reward = balance.add(balanceDiff);
}
return reward;
}
/**
@dev Removes longshorts from storage
@param longShortHash identifier of the LongShort to be removed
@param closingDate the latest date the LongShort should close
*/
function unlinkLongShortFromClosingDate(bytes32 longShortHash, uint closingDate) internal {
for (uint i = 0; i < activeClosingDates.length; i++) {
if (activeClosingDates[i] == closingDate) {
bytes32[] storage hashes = longShortHashes[closingDate];
for (uint j = 0; j < hashes.length; j++) {
if (hashes[j] == longShortHash) {
delete hashes[j];
hashes.length--;
if (hashes.length == 0) {
delete activeClosingDates[i];
activeClosingDates.length--;
} else {
longShortHashes[closingDate] = hashes;
}
break;
}
}
break;
}
}
}
/**
@dev Function to ping a single LongShort with
Checks if the price has increased or decreased enough for a margin call.
Exercises the option when it's closing date is over expiry.
@param longShortHash the unique identifier of a LongShort
*/
function ping(bytes32 longShortHash) public {
/// Load the LongShort into memory
LongShort memory longShort = longShorts[longShortHash];
/// Get the latest price from the oracle
uint256 latestPrice = oracle.price(longShort.currencyPair);
/// Require that the Oracle has price information of the currency pair
require(latestPrice > 0, "Oracle doesn't have a price for this currency pair!");
/// Calculate the threshold for a margin call by
/// dividing the starting price with the leverage
uint256 diffThreshold = longShort.startingPrice.div(longShort.leverage);
/// Calculate the price difference between latest price
/// from the Oracle and the starting price of the LongShort
uint256 priceDiff = longShort.startingPrice > latestPrice ? longShort.startingPrice.sub(latestPrice) : latestPrice.sub(longShort.startingPrice);
/// Margin call
if (priceDiff >= diffThreshold) {
closeLongShort(longShortHash, latestPrice);
}
/// Option has expired
if (longShort.closingDate <= block.timestamp) {
closeLongShort(longShortHash, latestPrice);
}
}
/**
@dev Internal function to be called, when a ping causes expiry or a margin call
@param longShortHash the unique identifier of a LongShort
@param latestPrice the closing price of the LongShort
*/
function closeLongShort(bytes32 longShortHash, uint256 latestPrice) internal {
/// Load the LongShort into memory
LongShort memory longShort = longShorts[longShortHash];
/// Get the amount of positions in the LongShort for looping
uint positionsLength = positions[longShortHash].length;
/// Load the positions into memory
Position[] memory positionsForHash = positions[longShortHash];
/// Calculate and queue the rewards for each position,
/// and remove the positions from the LongShort
for (uint j = 0; j < positionsLength; j++) {
rewardableAddresses.push(positionsForHash[j].paymentAddress);
rewards[positionsForHash[j].paymentAddress] = rewards[positionsForHash[j].paymentAddress].add(calculateReward(
positionsForHash[j].isLong,
positionsForHash[j].balance,
longShort.leverage,
longShort.startingPrice,
latestPrice
));
delete positions[longShortHash];
}
/// Delete the LongShort from the blockchain
delete longShorts[longShortHash];
/// Unlink the LongShort from the closing date
unlinkLongShortFromClosingDate(longShortHash, longShort.closingDate);
}
/**
@dev Pays a reward to an address
*/
function withdrawReward(address _paymentAddress) public {
uint256 rewardBalance = rewards[_paymentAddress];
delete rewards[_paymentAddress];
for (uint i = 0; i < rewardableAddresses.length; i++) {
if (rewardableAddresses[i]==_paymentAddress) {
delete rewardableAddresses[i];
break;
}
}
rewardableAddresses.length--;
_paymentAddress.transfer(rewardBalance);
}
// GETTERS
/**
@dev Get all queued rewardable addresses
@return {
"_rewardableAddresses": "rewardable addresses in queue"
}
*/
function getRewardableAddresses() public view onlyOwner returns (address[] _rewardableAddresses) {
return rewardableAddresses;
}
/**
@dev Gets all active closing dates from the contract
@return {
"closingDates": "List of seconds from 1970."
}
*/
function getActiveClosingDates() public view returns (uint[] closingDates) {
return activeClosingDates;
}
/**
@dev Get LongShort identifiers/hashes by closing date.
Only callable by the owner.
@param closingDate closing date to get LongShorts for
@return {
"hashes": "Unique identifiers for the LongShorts expiring on the closingDate."
}
*/
function getLongShortHashes(uint closingDate) public view onlyOwner returns (bytes32[] hashes) {
return longShortHashes[closingDate];
}
/**
@dev Get a single LongShort with its identifier
Only callable by the owner.
@param longShortHash unique identifier for a LongShort
@return {
"currencyPair": "7-character representation of a currency pair. For example, ETH-USD",
"startingPrice": "self-explanatory",
"leverage": "self-explanatory"
}
*/
function getLongShort(bytes32 longShortHash) public view onlyOwner returns (bytes32 currencyPair, uint256 startingPrice, uint8 leverage) {
return (longShorts[longShortHash].currencyPair, longShorts[longShortHash].startingPrice, longShorts[longShortHash].leverage);
}
}
| Delete the LongShort from the blockchain | delete longShorts[longShortHash];
| 6,377,096 | [
1,
2613,
326,
3407,
4897,
628,
326,
16766,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1430,
1525,
4897,
87,
63,
5748,
4897,
2310,
15533,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.12;
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 Modifier to use in the initializer function of a contract when upgrade EVEN times.
*/
modifier initializerEven() {
require(initializing || isConstructor() || initialized, "Contract instance has already been initialized EVEN times");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = false;
}
_;
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;
}
contract Governable is Initializable {
address public governor;
event GovernorshipTransferred(address indexed previousGovernor, address indexed newGovernor);
/**
* @dev Contract initializer.
* called once by the factory at time of deployment
*/
function initialize(address governor_) virtual public initializer {
governor = governor_;
emit GovernorshipTransferred(address(0), governor);
}
modifier governance() {
require(msg.sender == governor);
_;
}
/**
* @dev Allows the current governor to relinquish control of the contract.
* @notice Renouncing to governorship will leave the contract without an governor.
* It will not be possible to call the functions with the `governance`
* modifier anymore.
*/
function renounceGovernorship() public governance {
emit GovernorshipTransferred(governor, address(0));
governor = address(0);
}
/**
* @dev Allows the current governor to transfer control of the contract to a newGovernor.
* @param newGovernor The address to transfer governorship to.
*/
function transferGovernorship(address newGovernor) public governance {
_transferGovernorship(newGovernor);
}
/**
* @dev Transfers control of the contract to a newGovernor.
* @param newGovernor The address to transfer governorship to.
*/
function _transferGovernorship(address newGovernor) internal {
require(newGovernor != address(0));
emit GovernorshipTransferred(governor, newGovernor);
governor = newGovernor;
}
}
contract Configurable is Governable {
mapping (bytes32 => uint) internal config;
function getConfig(bytes32 key) public view returns (uint) {
return config[key];
}
function getConfig(bytes32 key, uint index) public view returns (uint) {
return config[bytes32(uint(key) ^ index)];
}
function getConfig(bytes32 key, address addr) public view returns (uint) {
return config[bytes32(uint(key) ^ uint(addr))];
}
function _setConfig(bytes32 key, uint value) internal {
if(config[key] != value)
config[key] = value;
}
function _setConfig(bytes32 key, uint index, uint value) internal {
_setConfig(bytes32(uint(key) ^ index), value);
}
function _setConfig(bytes32 key, address addr, uint value) internal {
_setConfig(bytes32(uint(key) ^ uint(addr)), value);
}
function setConfig(bytes32 key, uint value) external governance {
_setConfig(key, value);
}
function setConfig(bytes32 key, uint index, uint value) external governance {
_setConfig(bytes32(uint(key) ^ index), value);
}
function setConfig(bytes32 key, address addr, uint value) external governance {
_setConfig(bytes32(uint(key) ^ uint(addr)), value);
}
}
interface Minter {
event Minted(address indexed recipient, address reward_contract, uint minted);
function token() external view returns (address);
function controller() external view returns (address);
function minted(address, address) external view returns (uint);
function allowed_to_mint_for(address, address) external view returns (bool);
function mint(address gauge) external;
function mint_many(address[8] calldata gauges) external;
function mint_for(address gauge, address _for) external;
function toggle_approve_mint(address minting_user) external;
}
interface LiquidityGauge {
event Deposit(address indexed provider, uint value);
event Withdraw(address indexed provider, uint value);
event UpdateLiquidityLimit(address user, uint original_balance, uint original_supply, uint working_balance, uint working_supply);
function user_checkpoint (address addr) external returns (bool);
function claimable_tokens(address addr) external view returns (uint);
function claimable_reward(address addr) external view returns (uint);
function integrate_checkpoint() external view returns (uint);
function kick(address addr) external;
function set_approve_deposit(address addr, bool can_deposit) external;
function deposit(uint _value) external;
function deposit(uint _value, address addr) external;
function withdraw(uint _value) external;
function withdraw(uint _value, bool claim_rewards) external;
function claim_rewards() external;
function claim_rewards(address addr) external;
function minter() external view returns (address);
function crv_token() external view returns (address);
function lp_token() external view returns (address);
function controller() external view returns (address);
function voting_escrow() external view returns (address);
function balanceOf(address) external view returns (uint);
function totalSupply() external view returns (uint);
function future_epoch_time() external view returns (uint);
function approved_to_deposit(address, address) external view returns (bool);
function working_balances(address) external view returns (uint);
function working_supply() external view returns (uint);
function period() external view returns (int128);
function period_timestamp(uint) external view returns (uint);
function integrate_inv_supply(uint) external view returns (uint);
function integrate_inv_supply_of(address) external view returns (uint);
function integrate_checkpoint_of(address) external view returns (uint);
function integrate_fraction(address) external view returns (uint);
function inflation_rate() external view returns (uint);
function reward_contract() external view returns (address);
function rewarded_token() external view returns (address);
function reward_integral() external view returns (uint);
function reward_integral_for(address) external view returns (uint);
function rewards_for(address) external view returns (uint);
function claimed_rewards_for(address) external view returns (uint);
}
interface IStakingRewards {
// Views
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function rewards(address account) external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
// Mutative
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
// Events
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
}
interface IStakingRewards2 is IStakingRewards {
function totalMinted() external view returns (uint);
function weightOfGauge(address gauge) external view returns (uint);
function stakingPerLPT(address gauge) external view returns (uint);
function stakeTimeOf(address account) external view returns (uint);
function stakeAgeOf(address account) external view returns (uint);
function factorOf(address account) external view returns (uint);
function spendTimeOf(address account) external view returns (uint);
function spendAgeOf(address account) external view returns (uint);
function coinAgeOf(address account) external view returns (uint);
function spendCoinAge(address account, uint coinAge) external returns (uint);
event SpentCoinAge(address indexed gauge, address indexed account, uint coinAge);
}
contract SSimpleGauge is LiquidityGauge, Configurable {
using SafeMath for uint;
using TransferHelper for address;
address override public minter;
address override public crv_token;
address override public lp_token;
address override public controller;
address override public voting_escrow;
mapping(address => uint) override public balanceOf;
uint override public totalSupply;
uint override public future_epoch_time;
// caller -> recipient -> can deposit?
mapping(address => mapping(address => bool)) override public approved_to_deposit;
mapping(address => uint) override public working_balances;
uint override public working_supply;
// The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint
// All values are kept in units of being multiplied by 1e18
int128 override public period;
uint256[100000000000000000000000000000] override public period_timestamp;
// 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint
uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes
// 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint
mapping(address => uint) override public integrate_inv_supply_of;
mapping(address => uint) override public integrate_checkpoint_of;
// ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint
// Units: rate * t = already number of coins per address to issue
mapping(address => uint) override public integrate_fraction;
uint override public inflation_rate;
// For tracking external rewards
address override public reward_contract;
address override public rewarded_token;
uint override public reward_integral;
mapping(address => uint) override public reward_integral_for;
mapping(address => uint) override public rewards_for;
mapping(address => uint) override public claimed_rewards_for;
uint public span;
uint public end;
function initialize(address governor, address _minter, address _lp_token) public initializer {
super.initialize(governor);
minter = _minter;
crv_token = Minter(_minter).token();
lp_token = _lp_token;
IERC20(lp_token).totalSupply(); // just check
}
function setSpan(uint _span, bool isLinear) virtual external governance {
span = _span;
if(isLinear)
end = now + _span;
else
end = 0;
}
function kick(address addr) virtual override external {
_checkpoint(addr, true);
}
function set_approve_deposit(address addr, bool can_deposit) virtual override external {
approved_to_deposit[addr][msg.sender] = can_deposit;
}
function deposit(uint amount) virtual override external {
deposit(amount, msg.sender);
}
function deposit(uint amount, address addr) virtual override public {
require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved');
_checkpoint(addr, true);
_deposit(addr, amount);
balanceOf[addr] = balanceOf[addr].add(amount);
totalSupply = totalSupply.add(amount);
emit Deposit(addr, amount);
}
function _deposit(address addr, uint amount) virtual internal {
lp_token.safeTransferFrom(addr, address(this), amount);
}
function withdraw() virtual external {
withdraw(balanceOf[msg.sender], true);
}
function withdraw(uint amount) virtual override external {
withdraw(amount, true);
}
function withdraw(uint amount, bool claim_rewards) virtual override public {
_checkpoint(msg.sender, claim_rewards);
totalSupply = totalSupply.sub(amount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount);
_withdraw(msg.sender, amount);
emit Withdraw(msg.sender, amount);
}
function _withdraw(address to, uint amount) virtual internal {
lp_token.safeTransfer(to, amount);
}
function claimable_reward(address) virtual override public view returns (uint) {
return 0;
}
function claim_rewards() virtual override public {
return claim_rewards(msg.sender);
}
function claim_rewards(address) virtual override public {
return;
}
function _checkpoint_rewards(address, bool) virtual internal {
return;
}
function claimable_tokens(address addr) virtual override public view returns (uint amount) {
if(span == 0 || totalSupply == 0)
return 0;
amount = SMinter(minter).quotas(address(this));
amount = amount.mul(balanceOf[addr]).div(totalSupply);
uint lasttime = integrate_checkpoint_of[addr];
if(end == 0) { // isNonLinear, endless
if(now.sub(lasttime) < span)
amount = amount.mul(now.sub(lasttime)).div(span);
}else if(now < end)
amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime));
else if(lasttime >= end)
amount = 0;
}
function _checkpoint(address addr, uint amount) virtual internal {
if(amount > 0) {
integrate_fraction[addr] = integrate_fraction[addr].add(amount);
address teamAddr = address(config['teamAddr']);
uint teamRatio = config['teamRatio'];
if(teamAddr != address(0) && teamRatio != 0)
integrate_fraction[teamAddr] = integrate_fraction[teamAddr].add(amount.mul(teamRatio).div(1 ether));
}
}
function _checkpoint(address addr, bool _claim_rewards) virtual internal {
uint amount = claimable_tokens(addr);
_checkpoint(addr, amount);
_checkpoint_rewards(addr, _claim_rewards);
integrate_checkpoint_of[addr] = now;
}
function user_checkpoint(address addr) virtual override external returns (bool) {
_checkpoint(addr, true);
return true;
}
function integrate_checkpoint() override external view returns (uint) {
return now;
}
}
c
SExactGauge is LiquidityGauge, Configurable {
using SafeMath for uint;
using TransferHelper for address;
bytes32 internal constant _devAddr_ = 'devAddr';
bytes32 internal constant _devRatio_ = 'devRatio';
bytes32 internal constant _ecoAddr_ = 'ecoAddr';
bytes32 internal constant _ecoRatio_ = 'ecoRatio';
bytes32 internal constant _claim_rewards_ = 'claim_rewards';
address override public minter;
address override public crv_token;
address override public lp_token;
address override public controller;
address override public voting_escrow;
mapping(address => uint) override public balanceOf;
uint override public totalSupply;
uint override public future_epoch_time;
// caller -> recipient -> can deposit?
mapping(address => mapping(address => bool)) override public approved_to_deposit;
mapping(address => uint) override public working_balances;
uint override public working_supply;
// The goal is to be able to calculate ∫(rate * balance / totalSupply dt) from 0 till checkpoint
// All values are kept in units of being multiplied by 1e18
int128 override public period;
uint256[100000000000000000000000000000] override public period_timestamp;
// 1e18 * ∫(rate(t) / totalSupply(t) dt) from 0 till checkpoint
uint256[100000000000000000000000000000] override public integrate_inv_supply; // bump epoch when rate() changes
// 1e18 * ∫(rate(t) / totalSupply(t) dt) from (last_action) till checkpoint
mapping(address => uint) override public integrate_inv_supply_of;
mapping(address => uint) override public integrate_checkpoint_of;
// ∫(balance * rate(t) / totalSupply(t) dt) from 0 till checkpoint
// Units: rate * t = already number of coins per address to issue
mapping(address => uint) override public integrate_fraction;
uint override public inflation_rate;
// For tracking external rewards
address override public reward_contract;
address override public rewarded_token;
mapping(address => uint) public reward_integral_; // rewarded_token => reward_integral
mapping(address => mapping(address => uint)) public reward_integral_for_; // recipient => rewarded_token => reward_integral_for
mapping(address => mapping(address => uint)) public rewards_for_;
mapping(address => mapping(address => uint)) public claimed_rewards_for_;
uint public span;
uint public end;
mapping(address => uint) public sumMiningPerOf;
uint public sumMiningPer;
uint public bufReward;
uint public lasttime;
function initialize(address governor, address _minter, address _lp_token) public virtual initializer {
super.initialize(governor);
minter = _minter;
crv_token = Minter(_minter).token();
lp_token = _lp_token;
IERC20(lp_token).totalSupply(); // just check
}
function setSpan(uint _span, bool isLinear) virtual external governance {
span = _span;
if(isLinear)
end = now + _span;
else
end = 0;
if(lasttime == 0)
lasttime = now;
}
function kick(address addr) virtual override external {
_checkpoint(addr, true);
}
function set_approve_deposit(address addr, bool can_deposit) virtual override external {
approved_to_deposit[addr][msg.sender] = can_deposit;
}
function deposit(uint amount) virtual override external {
deposit(amount, msg.sender);
}
function deposit(uint amount, address addr) virtual override public {
require(addr == msg.sender || approved_to_deposit[msg.sender][addr], 'Not approved');
_checkpoint(addr, config[_claim_rewards_] == 0 ? false : true);
_deposit(addr, amount);
balanceOf[msg.sender] = balanceOf[msg.sender].add(amount);
totalSupply = totalSupply.add(amount);
emit Deposit(msg.sender, amount);
}
function _deposit(address addr, uint amount) virtual internal {
lp_token.safeTransferFrom(addr, address(this), amount);
}
function withdraw() virtual external {
withdraw(balanceOf[msg.sender]);
}
function withdraw(uint amount) virtual override public {
withdraw(amount, config[_claim_rewards_] == 0 ? false : true);
}
function withdraw(uint amount, bool _claim_rewards) virtual override public {
_checkpoint(msg.sender, _claim_rewards);
totalSupply = totalSupply.sub(amount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount);
_withdraw(msg.sender, amount);
emit Withdraw(msg.sender, amount);
}
function _withdraw(address to, uint amount) virtual internal {
lp_token.safeTransfer(to, amount);
}
function claimable_reward(address addr) virtual override public view returns (uint) {
addr;
return 0;
}
function claim_rewards() virtual override public {
return claim_rewards(msg.sender);
}
function claim_rewards(address) virtual override public {
return;
}
function _checkpoint_rewards(address, bool) virtual internal {
return;
}
function claimable_tokens(address addr) virtual override public view returns (uint r) {
r = integrate_fraction[addr].sub(Minter(minter).minted(addr, address(this)));
r = r.add(_claimable_last(addr, claimableDelta(), sumMiningPer, sumMiningPerOf[addr]));
}
function _claimable_last(address addr, uint delta, uint sumPer, uint lastSumPer) virtual internal view returns (uint amount) {
if(span == 0 || totalSupply == 0)
return 0;
amount = sumPer.sub(lastSumPer);
amount = amount.add(delta.mul(1 ether).div(totalSupply));
amount = amount.mul(balanceOf[addr]).div(1 ether);
}
function claimableDelta() virtual internal view returns(uint amount) {
if(span == 0 || totalSupply == 0)
return 0;
amount = SMinter(minter).quotas(address(this)).sub(bufReward);
if(end == 0) { // isNonLinear, endless
if(now.sub(lasttime) < span)
amount = amount.mul(now.sub(lasttime)).div(span);
}else if(now < end)
amount = amount.mul(now.sub(lasttime)).div(end.sub(lasttime));
else if(lasttime >= end)
amount = 0;
}
function _checkpoint(address addr, uint amount) virtual internal {
if(amount > 0) {
integrate_fraction[addr] = integrate_fraction[addr].add(amount);
addr = address(config[_devAddr_]);
uint ratio = config[_devRatio_];
if(addr != address(0) && ratio != 0)
integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether));
addr = address(config[_ecoAddr_]);
ratio = config[_ecoRatio_];
if(addr != address(0) && ratio != 0)
integrate_fraction[addr] = integrate_fraction[addr].add(amount.mul(ratio).div(1 ether));
}
}
function _checkpoint(address addr, bool _claim_rewards) virtual internal {
if(span == 0 || totalSupply == 0)
return;
uint delta = claimableDelta();
uint amount = _claimable_last(addr, delta, sumMiningPer, sumMiningPerOf[addr]);
if(delta != amount)
bufReward = bufReward.add(delta).sub(amount);
if(delta > 0)
sumMiningPer = sumMiningPer.add(delta.mul(1 ether).div(totalSupply));
if(sumMiningPerOf[addr] != sumMiningPer)
sumMiningPerOf[addr] = sumMiningPer;
lasttime = now;
_checkpoint(addr, amount);
_checkpoint_rewards(addr, _claim_rewards);
}
function user_checkpoint(address addr) virtual override external returns (bool) {
_checkpoint(addr, config[_claim_rewards_] == 0 ? false : true);
return true;
}
function integrate_checkpoint() override external view returns (uint) {
return lasttime;
}
function reward_integral() virtual override external view returns (uint) {
return reward_integral_[rewarded_token];
}
function reward_integral_for(address addr) virtual override external view returns (uint) {
return reward_integral_for_[addr][rewarded_token];
}
function rewards_for(address addr) virtual override external view returns (uint) {
return rewards_for_[addr][rewarded_token];
}
function claimed_rewards_for(address addr) virtual override external view returns (uint) {
return claimed_rewards_for_[addr][rewarded_token];
}
}
contra
uge is SExactGauge {
address[] public rewards;
//mapping(address => mapping(address =>uint)) internal sumRewardPerOf_; // recipient => rewarded_token => can sumRewardPerOf // obsolete, instead of reward_integral_
//mapping(address => uint) internal sumRewardPer_; // rewarded_token => can sumRewardPerOf // obsolete, instead of reward_integral_for_
function initialize(address governor, address _minter, address _lp_token, address _nestGauge, address[] memory _moreRewards) public initializer {
super.initialize(governor, _minter, _lp_token);
reward_contract = _nestGauge;
rewarded_token = LiquidityGauge(_nestGauge).crv_token();
rewards = _moreRewards;
rewards.push(rewarded_token);
address rewarded_token2 = LiquidityGauge(_nestGauge).rewarded_token();
if(rewarded_token2 != address(0))
rewards.push(rewarded_token2);
LiquidityGauge(_nestGauge).integrate_checkpoint(); // just check
for(uint i=0; i<_moreRewards.length; i++)
IERC20(_moreRewards[i]).totalSupply(); // just check
}
function _deposit(address from, uint amount) virtual override internal {
super._deposit(from, amount); // lp_token.safeTransferFrom(from, address(this), amount);
lp_token.safeApprove(reward_contract, amount);
LiquidityGauge(reward_contract).deposit(amount);
}
function _withdraw(address to, uint amount) virtual override internal {
LiquidityGauge(reward_contract).withdraw(amount);
super._withdraw(to, amount); // lp_token.safeTransfer(to, amount);
}
function claim_rewards(address to) virtual override public {
if(span == 0 || totalSupply == 0)
return;
_checkpoint_rewards(to, true);
for(uint i=0; i<rewards.length; i++) {
uint amount = rewards_for_[to][rewards[i]].sub(claimed_rewards_for_[to][rewards[i]]);
if(amount > 0) {
rewards[i].safeTransfer(to, amount);
claimed_rewards_for_[to][rewards[i]] = rewards_for_[to][rewards[i]];
}
}
}
function _checkpoint_rewards(address addr, bool _claim_rewards) virtual override internal {
if(span == 0 || totalSupply == 0)
return;
uint[] memory drs = new uint[](rewards.length);
if(_claim_rewards) {
for(uint i=0; i<drs.length; i++)
drs[i] = IERC20(rewards[i]).balanceOf(address(this));
Minter(LiquidityGauge(reward_contract).minter()).mint(reward_contract);
LiquidityGauge(reward_contract).claim_rewards();
for(uint i=0; i<drs.length; i++)
drs[i] = IERC20(rewards[i]).balanceOf(address(this)).sub(drs[i]);
}
for(uint i=0; i<drs.length; i++) {
uint amount = _claimable_last(addr, drs[i], reward_integral_[rewards[i]], reward_integral_for_[addr][rewards[i]]);
if(amount > 0)
rewards_for_[addr][rewards[i]] = rewards_for_[addr][rewards[i]].add(amount);
if(drs[i] > 0)
reward_integral_[rewards[i]] = reward_integral_[rewards[i]].add(drs[i].mul(1 ether).div(totalSupply));
if(reward_integral_for_[addr][rewards[i]] != reward_integral_[rewards[i]])
reward_integral_for_[addr][rewards[i]] = reward_integral_[rewards[i]];
}
}
function claimable_reward(address addr) virtual override public view returns (uint r) {
//uint delta = LiquidityGauge(reward_contract).claimable_tokens(address(this)); // Error: Mutable call in static context
uint delta = LiquidityGauge(reward_contract).integrate_fraction(address(this)).sub(Minter(LiquidityGauge(reward_contract).minter()).minted(address(this), reward_contract));
r = _claimable_last(addr, delta, reward_integral_[rewarded_token], reward_integral_for_[addr][rewarded_token]);
r = r.add(rewards_for_[addr][rewarded_token].sub(claimed_rewards_for_[addr][rewarded_token]));
}
function claimable_reward2(address addr) virtual public view returns (uint r) {
uint delta = LiquidityGauge(reward_contract).claimable_reward(address(this)).sub(LiquidityGauge(reward_contract).claimed_rewards_for(address(this)));
address reward2 = LiquidityGauge(reward_contract).rewarded_token();
r = _claimable_last(addr, delta, reward_integral_[reward2], reward_integral_for_[addr][reward2]);
r = r.add(rewards_for_[addr][reward2].sub(claimed_rewards_for_[addr][reward2]));
}
function claimable_reward(address addr, address reward) virtual public view returns (uint r) {
r = _claimable_last(addr, 0, reward_integral_[reward], reward_integral_for_[addr][reward]);
r = r.add(rewards_for_[addr][reward].sub(claimed_rewards_for_[addr][reward]));
}
function claimed_rewards_for2(address addr) virtual public view returns (uint) {
return claimed_rewards_for_[addr][LiquidityGauge(reward_contract).rewarded_token()];
}
function rewards_for2(address addr) virtual public view returns (uint) {
return rewards_for_[addr][LiquidityGauge(reward_contract).rewarded_token()];
}
}
contrac
is Minter, Configurable {
using SafeMath for uint;
using Address for address payable;
using TransferHelper for address;
bytes32 internal constant _allowContract_ = 'allowContract';
bytes32 internal constant _allowlist_ = 'allowlist';
bytes32 internal constant _blocklist_ = 'blocklist';
address override public token;
address override public controller;
mapping(address => mapping(address => uint)) override public minted; // user => reward_contract => value
mapping(address => mapping(address => bool)) override public allowed_to_mint_for; // minter => user => can mint?
mapping(address => uint) public quotas; // reward_contract => quota;
function initialize(address governor, address token_) public initializer {
super.initialize(governor);
token = token_;
}
function setGaugeQuota(address gauge, uint quota) public governance {
quotas[gauge] = quota;
}
function mint(address gauge) virtual override public {
mint_for(gauge, msg.sender);
}
function mint_many(address[8] calldata gauges) virtual override external {
for(uint i=0; i<gauges.length; i++)
mint(gauges[i]);
}
function mint_many(address[] calldata gauges) virtual external {
for(uint i=0; i<gauges.length; i++)
mint(gauges[i]);
}
function mint_for(address gauge, address _for) virtual override public {
require(_for == msg.sender || allowed_to_mint_for[msg.sender][_for], 'Not approved');
require(quotas[gauge] > 0, 'No quota');
require(getConfig(_blocklist_, msg.sender) == 0, 'In blocklist');
bool isContract = msg.sender.isContract();
require(!isContract || config[_allowContract_] != 0 || getConfig(_allowlist_, msg.sender) != 0, 'No allowContract');
LiquidityGauge(gauge).user_checkpoint(_for);
uint total_mint = LiquidityGauge(gauge).integrate_fraction(_for);
uint to_mint = total_mint.sub(minted[_for][gauge]);
if(to_mint != 0) {
quotas[gauge] = quotas[gauge].sub(to_mint);
token.safeTransfer(_for, to_mint);
minted[_for][gauge] = total_mint;
emit Minted(_for, gauge, total_mint);
}
}
function toggle_approve_mint(address minting_user) virtual override external {
allowed_to_mint_for[minting_user][msg.sender] = !allowed_to_mint_for[minting_user][msg.sender];
}
}
/*
// he
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;
}
}
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;
}
function sqrt(uint x)public pure returns(uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
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);
}
}
}
}
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 ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) public _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 public _totalSupply;
string internal _name;
string internal _symbol;
uint8 internal _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 virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This 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 { }
}
contract SfgToken is ERC20 {
constructor(address SfgFarm) ERC20("Stable Finance Governance Token", "SFG") public {
uint8 decimals = 18;
_setupDecimals(decimals);
_mint(SfgFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000
}
}
contract SfyToken is ERC20 {
constructor(address SfyFarm) ERC20("Stable Finance Yield Token", "SFY") public {
uint8 decimals = 18;
_setupDecimals(decimals);
_mint(SfyFarm, 21000000 * 10 ** uint256(decimals)); // 100%, 21000000
}
}
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
contract TurboGauge is SExactGauge {
address public staking;
mapping(address => uint) public lastTurboOf;
uint public lastTurboSupply;
function initialize(address governor, address _minter, address _lp_token, address _staking) virtual public initializer {
super.initialize(governor, _minter, _lp_token);
staking = _staking;
}
function ratioStaking(address addr) public view returns (uint r) {
r = IStakingRewards2(staking).balanceOf(addr);
r = r.mul(1 ether).div(IStakingRewards2(staking).stakingPerLPT(address(this)));
r = r.mul(1 ether).div(balanceOf[addr]);
if(now > lasttime)
r = r.mul(IStakingRewards2(staking).spendAgeOf(addr)).div(now.sub(lasttime));
}
function factorOf(address addr) public view returns (uint f) {
f = IStakingRewards2(staking).factorOf(addr);
uint r = ratioStaking(addr);
if(r < 1 ether)
f = f.sub(1 ether).mul(r).div(1 ether).add(1 ether);
}
function virtualBalanceOf(address addr) virtual public view returns (uint) {
if(span == 0 || totalSupply == 0)
return balanceOf[addr];
if(now == lasttime)
return balanceOf[addr].add(lastTurboOf[addr]);
return balanceOf[addr].mul(factorOf(addr)).div(1 ether);
}
function virtualTotalSupply() virtual public view returns (uint) {
return totalSupply.add(lastTurboSupply);
}
function _virtualTotalSupply(address addr, uint vbo) virtual internal view returns (uint) {
return virtualTotalSupply().add(vbo).sub(balanceOf[addr].add(lastTurboOf[addr]));
}
function _virtual_claimable_last(uint delta, uint sumPer, uint lastSumPer, uint vbo, uint _vts) virtual internal view returns (uint amount) {
if(span == 0 || totalSupply == 0)
return 0;
amount = sumPer.sub(lastSumPer);
amount = amount.add(delta.mul(1 ether).div(_vts));
amount = amount.mul(vbo).div(1 ether);
}
function _checkpoint(address addr, bool _claim_rewards) virtual override internal {
if(span == 0 || totalSupply == 0)
return;
uint vbo = virtualBalanceOf(addr);
uint _vts = _virtualTotalSupply(addr, vbo);
uint delta = claimableDelta();
uint amount = _virtual_claimable_last(delta, sumMiningPer, sumMiningPerOf[addr], vbo, _vts);
if(delta != amount)
bufReward = bufReward.add(delta).sub(amount);
if(delta > 0)
sumMiningPer = sumMiningPer.add(delta.mul(1 ether).div(_vts));
if(sumMiningPerOf[addr] != sumMiningPer)
sumMiningPerOf[addr] = sumMiningPer;
if(lastTurboOf[addr] != vbo.sub(balanceOf[addr]))
lastTurboOf[addr] = vbo.sub(balanceOf[addr]);
if(lastTurboSupply != _vts.sub(totalSupply))
lastTurboSupply = _vts.sub(totalSupply);
lasttime = now;
_checkpoint(addr, amount);
_checkpoint_rewards(addr, _claim_rewards);
}
}
| * @dev Indicates that the contract has been initialized./* @dev Indicates that the contract is in the process of being initialized./* @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;
}
}
| 7,336,164 | [
1,
23741,
716,
326,
6835,
711,
2118,
6454,
18,
19,
225,
18336,
716,
326,
6835,
353,
316,
326,
1207,
434,
3832,
6454,
18,
19,
225,
12832,
358,
999,
316,
326,
12562,
445,
434,
279,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
9606,
12562,
1435,
288,
203,
203,
203,
565,
2583,
12,
6769,
6894,
747,
353,
6293,
1435,
747,
401,
13227,
16,
315,
8924,
791,
711,
1818,
2118,
6454,
8863,
203,
203,
203,
203,
203,
203,
565,
1426,
353,
27046,
1477,
273,
401,
6769,
6894,
31,
203,
203,
203,
565,
309,
261,
291,
27046,
1477,
13,
288,
203,
203,
203,
1377,
22584,
273,
638,
31,
203,
203,
203,
1377,
6454,
273,
638,
31,
203,
203,
203,
565,
289,
203,
203,
203,
203,
203,
203,
565,
389,
31,
203,
203,
203,
203,
203,
203,
565,
309,
261,
291,
27046,
1477,
13,
288,
203,
203,
203,
1377,
22584,
273,
629,
31,
203,
203,
203,
565,
289,
203,
203,
203,
225,
289,
203,
203,
203,
203,
203,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.22 <0.6.0;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
contract LibMath {
using SafeMath for uint256;
function getPartialAmount(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
partialAmount = numerator.mul(target).div(denominator);
}
function getFeeAmount(
uint256 numerator,
uint256 target
)
internal
pure
returns (uint256 feeAmount)
{
feeAmount = numerator.mul(target).div(1 ether); // todo: constants
}
}
contract LibOrder {
struct Order {
uint256 makerSellAmount;
uint256 makerBuyAmount;
uint256 takerSellAmount;
uint256 salt;
uint256 expiration;
address taker;
address maker;
address makerSellToken;
address makerBuyToken;
}
struct OrderInfo {
uint256 filledAmount;
bytes32 hash;
uint8 status;
}
struct OrderFill {
uint256 makerFillAmount;
uint256 takerFillAmount;
uint256 takerFeePaid;
uint256 exchangeFeeReceived;
uint256 referralFeeReceived;
uint256 makerFeeReceived;
}
enum OrderStatus {
INVALID_SIGNER,
INVALID_TAKER_AMOUNT,
INVALID_MAKER_AMOUNT,
FILLABLE,
EXPIRED,
FULLY_FILLED,
CANCELLED
}
function getHash(Order memory order)
public
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
order.maker,
order.makerSellToken,
order.makerSellAmount,
order.makerBuyToken,
order.makerBuyAmount,
order.salt,
order.expiration
)
);
}
function getPrefixedHash(Order memory order)
public
pure
returns (bytes32)
{
bytes32 orderHash = getHash(order);
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash));
}
}
contract LibSignatureValidator {
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
}
contract IKyberNetworkProxy {
function getExpectedRate(address src, address dest, uint srcQty) public view
returns (uint expectedRate, uint slippageRate);
function trade(
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId
) public payable returns(uint256);
}
contract LibKyberData {
struct KyberData {
uint256 expectedReceiveAmount;
uint256 rate;
uint256 value;
address givenToken;
address receivedToken;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev 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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev 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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract IExchangeUpgradability {
uint8 public VERSION;
event FundsMigrated(address indexed user, address indexed newExchange);
function allowOrRestrictMigrations() external;
function migrateFunds(address[] calldata tokens) external;
function migrateEthers() private;
function migrateTokens(address[] memory tokens) private;
function importEthers(address user) external payable;
function importTokens(address tokenAddress, uint256 tokenAmount, address user) external;
}
contract LibCrowdsale {
using SafeMath for uint256;
struct Crowdsale {
uint256 startBlock;
uint256 endBlock;
uint256 hardCap;
uint256 leftAmount;
uint256 tokenRatio;
uint256 minContribution;
uint256 maxContribution;
uint256 weiRaised;
address wallet;
}
enum ContributionStatus {
CROWDSALE_NOT_OPEN,
MIN_CONTRIBUTION,
MAX_CONTRIBUTION,
HARDCAP_REACHED,
VALID
}
enum CrowdsaleStatus {
INVALID_START_BLOCK,
INVALID_END_BLOCK,
INVALID_TOKEN_RATIO,
INVALID_LEFT_AMOUNT,
VALID
}
function getCrowdsaleStatus(Crowdsale memory crowdsale)
public
view
returns (CrowdsaleStatus)
{
if(crowdsale.startBlock < block.number) {
return CrowdsaleStatus.INVALID_START_BLOCK;
}
if(crowdsale.endBlock < crowdsale.startBlock) {
return CrowdsaleStatus.INVALID_END_BLOCK;
}
if(crowdsale.tokenRatio == 0) {
return CrowdsaleStatus.INVALID_TOKEN_RATIO;
}
uint256 tokenForSale = crowdsale.hardCap.mul(crowdsale.tokenRatio);
if(tokenForSale != crowdsale.leftAmount) {
return CrowdsaleStatus.INVALID_LEFT_AMOUNT;
}
return CrowdsaleStatus.VALID;
}
function isOpened(uint256 startBlock, uint256 endBlock)
internal
view
returns (bool)
{
return (block.number >= startBlock && block.number <= endBlock);
}
function isFinished(uint256 endBlock)
internal
view
returns (bool)
{
return block.number > endBlock;
}
}
/**
* @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);
function decimals() external view returns (uint8);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type,
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* 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.
*
* > 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.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
contract ExchangeStorage is Ownable {
/**
* @dev The minimum fee rate that the maker will receive
* Note: 20% = 20 * 10^16
*/
uint256 constant internal minMakerFeeRate = 200000000000000000;
/**
* @dev The maximum fee rate that the maker will receive
* Note: 90% = 90 * 10^16
*/
uint256 constant internal maxMakerFeeRate = 900000000000000000;
/**
* @dev The minimum fee rate that the taker will pay
* Note: 0.1% = 0.1 * 10^16
*/
uint256 constant internal minTakerFeeRate = 1000000000000000;
/**
* @dev The maximum fee rate that the taker will pay
* Note: 1% = 1 * 10^16
*/
uint256 constant internal maxTakerFeeRate = 10000000000000000;
/**
* @dev The referrer will receive 10% from each taker fee.
* Note: 10% = 10 * 10^16
*/
uint256 constant internal referralFeeRate = 100000000000000000;
/**
* @dev The amount of percentage the maker will receive from each taker fee.
* Note: Initially: 50% = 50 * 10^16
*/
uint256 public makerFeeRate;
/**
* @dev The amount of percentage the will pay for taking an order.
* Note: Initially: 0.2% = 0.2 * 10^16
*/
uint256 public takerFeeRate;
/**
* @dev 2-level map: tokenAddress -> userAddress -> balance
*/
mapping(address => mapping(address => uint256)) internal balances;
/**
* @dev map: orderHash -> filled amount
*/
mapping(bytes32 => uint256) internal filled;
/**
* @dev map: orderHash -> isCancelled
*/
mapping(bytes32 => bool) internal cancelled;
/**
* @dev map: user -> userReferrer
*/
mapping(address => address) internal referrals;
/**
* @dev The address where all exchange fees (0,08%) are kept.
* Node: multisig wallet
*/
address public feeAccount;
/**
* @return return the balance of `token` for certain `user`
*/
function getBalance(
address user,
address token
)
public
view
returns (uint256)
{
return balances[token][user];
}
/**
* @return return the balance of multiple tokens for certain `user`
*/
function getBalances(
address user,
address[] memory token
)
public
view
returns(uint256[] memory balanceArray)
{
balanceArray = new uint256[](token.length);
for(uint256 index = 0; index < token.length; index++) {
balanceArray[index] = balances[token[index]][user];
}
}
/**
* @return return the filled amount of order specified by `orderHash`
*/
function getFill(
bytes32 orderHash
)
public
view
returns (uint256)
{
return filled[orderHash];
}
/**
* @return return the filled amount of multple orders specified by `orderHash` array
*/
function getFills(
bytes32[] memory orderHash
)
public
view
returns (uint256[] memory filledArray)
{
filledArray = new uint256[](orderHash.length);
for(uint256 index = 0; index < orderHash.length; index++) {
filledArray[index] = filled[orderHash[index]];
}
}
/**
* @return return true(false) if order specified by `orderHash` is(not) cancelled
*/
function getCancel(
bytes32 orderHash
)
public
view
returns (bool)
{
return cancelled[orderHash];
}
/**
* @return return array of true(false) if orders specified by `orderHash` array are(not) cancelled
*/
function getCancels(
bytes32[] memory orderHash
)
public
view
returns (bool[]memory cancelledArray)
{
cancelledArray = new bool[](orderHash.length);
for(uint256 index = 0; index < orderHash.length; index++) {
cancelledArray[index] = cancelled[orderHash[index]];
}
}
/**
* @return return the referrer address of `user`
*/
function getReferral(
address user
)
public
view
returns (address)
{
return referrals[user];
}
/**
* @return set new rate for the maker fee received
*/
function setMakerFeeRate(
uint256 newMakerFeeRate
)
external
onlyOwner
{
require(
newMakerFeeRate >= minMakerFeeRate &&
newMakerFeeRate <= maxMakerFeeRate,
"INVALID_MAKER_FEE_RATE"
);
makerFeeRate = newMakerFeeRate;
}
/**
* @return set new rate for the taker fee paid
*/
function setTakerFeeRate(
uint256 newTakerFeeRate
)
external
onlyOwner
{
require(
newTakerFeeRate >= minTakerFeeRate &&
newTakerFeeRate <= maxTakerFeeRate,
"INVALID_TAKER_FEE_RATE"
);
takerFeeRate = newTakerFeeRate;
}
/**
* @return set new fee account
*/
function setFeeAccount(
address newFeeAccount
)
external
onlyOwner
{
feeAccount = newFeeAccount;
}
}
/**
* @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);
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");
}
}
}
contract Exchange is LibMath, LibOrder, LibSignatureValidator, ExchangeStorage {
using SafeMath for uint256;
/**
* @dev emitted when a trade is executed
*/
event Trade(
address indexed makerAddress, // Address that created the order
address indexed takerAddress, // Address that filled the order
bytes32 indexed orderHash, // Hash of the order
address makerFilledAsset, // Address of assets filled for maker
address takerFilledAsset, // Address of assets filled for taker
uint256 makerFilledAmount, // Amount of assets filled for maker
uint256 takerFilledAmount, // Amount of assets filled for taker
uint256 takerFeePaid, // Amount of fee paid by the taker
uint256 makerFeeReceived, // Amount of fee received by the maker
uint256 referralFeeReceived // Amount of fee received by the referrer
);
/**
* @dev emitted when a cancel order is executed
*/
event Cancel(
address indexed makerBuyToken, // Address of asset being bought.
address makerSellToken, // Address of asset being sold.
address indexed maker, // Address that created the order
bytes32 indexed orderHash // Hash of the order
);
/**
* @dev Compute the status of an order.
* Should be called before a contract execution is performet in order to not waste gas.
* @return OrderStatus.FILLABLE if the order is valid for taking.
* Note: See LibOrder.sol to see all statuses
*/
function getOrderInfo(
uint256 partialAmount,
Order memory order
)
public
view
returns (OrderInfo memory orderInfo)
{
// Compute the order hash
orderInfo.hash = getPrefixedHash(order);
// Fetch filled amount
orderInfo.filledAmount = filled[orderInfo.hash];
// Check taker balance
if(balances[order.makerBuyToken][order.taker] < order.takerSellAmount) {
orderInfo.status = uint8(OrderStatus.INVALID_TAKER_AMOUNT);
return orderInfo;
}
// Check maker balance
if(balances[order.makerSellToken][order.maker] < partialAmount) {
orderInfo.status = uint8(OrderStatus.INVALID_MAKER_AMOUNT);
return orderInfo;
}
// Check if order is filled
if (orderInfo.filledAmount.add(order.takerSellAmount) > order.makerBuyAmount) {
orderInfo.status = uint8(OrderStatus.FULLY_FILLED);
return orderInfo;
}
// Check for expiration
if (block.number >= order.expiration) {
orderInfo.status = uint8(OrderStatus.EXPIRED);
return orderInfo;
}
// Check if order has been cancelled
if (cancelled[orderInfo.hash]) {
orderInfo.status = uint8(OrderStatus.CANCELLED);
return orderInfo;
}
orderInfo.status = uint8(OrderStatus.FILLABLE);
return orderInfo;
}
/**
* @dev Execute a trade based on the input order and signature.
* Reverts if order is not valid
*/
function trade(
Order memory order,
bytes memory signature
)
public
{
bool result = _trade(order, signature);
require(result, "INVALID_TRADE");
}
/**
* @dev Execute a trade based on the input order and signature.
* If the order is valid returns true.
*/
function _trade(
Order memory order,
bytes memory signature
)
internal
returns(bool)
{
order.taker = msg.sender;
uint256 takerReceivedAmount = getPartialAmount(
order.makerSellAmount,
order.makerBuyAmount,
order.takerSellAmount
);
OrderInfo memory orderInfo = getOrderInfo(takerReceivedAmount, order);
uint8 status = assertTakeOrder(orderInfo.hash, orderInfo.status, order.maker, signature);
if(status != uint8(OrderStatus.FILLABLE)) {
return false;
}
OrderFill memory orderFill = getOrderFillResult(takerReceivedAmount, order);
executeTrade(order, orderFill);
filled[orderInfo.hash] = filled[orderInfo.hash].add(order.takerSellAmount);
emit Trade(
order.maker,
order.taker,
orderInfo.hash,
order.makerBuyToken,
order.makerSellToken,
orderFill.makerFillAmount,
orderFill.takerFillAmount,
orderFill.takerFeePaid,
orderFill.makerFeeReceived,
orderFill.referralFeeReceived
);
return true;
}
/**
* @dev Cancel an order if msg.sender is the order signer.
*/
function cancelSingleOrder(
Order memory order,
bytes memory signature
)
public
{
bytes32 orderHash = getPrefixedHash(order);
require(
recover(orderHash, signature) == msg.sender,
"INVALID_SIGNER"
);
require(
cancelled[orderHash] == false,
"ALREADY_CANCELLED"
);
cancelled[orderHash] = true;
emit Cancel(
order.makerBuyToken,
order.makerSellToken,
msg.sender,
orderHash
);
}
/**
* @dev Computation of the following properties based on the order input:
* takerFillAmount -> amount of assets received by the taker
* makerFillAmount -> amount of assets received by the maker
* takerFeePaid -> amount of fee paid by the taker (0.2% of takerFillAmount)
* makerFeeReceived -> amount of fee received by the maker (50% of takerFeePaid)
* referralFeeReceived -> amount of fee received by the taker referrer (10% of takerFeePaid)
* exchangeFeeReceived -> amount of fee received by the exchange (40% of takerFeePaid)
*/
function getOrderFillResult(
uint256 takerReceivedAmount,
Order memory order
)
internal
view
returns (OrderFill memory orderFill)
{
orderFill.takerFillAmount = takerReceivedAmount;
orderFill.makerFillAmount = order.takerSellAmount;
// 0.2% == 0.2*10^16
orderFill.takerFeePaid = getFeeAmount(
takerReceivedAmount,
takerFeeRate
);
// 50% of taker fee == 50*10^16
orderFill.makerFeeReceived = getFeeAmount(
orderFill.takerFeePaid,
makerFeeRate
);
// 10% of taker fee == 10*10^16
orderFill.referralFeeReceived = getFeeAmount(
orderFill.takerFeePaid,
referralFeeRate
);
// exchangeFee = (takerFeePaid - makerFeeReceived - referralFeeReceived)
orderFill.exchangeFeeReceived = orderFill.takerFeePaid.sub(
orderFill.makerFeeReceived).sub(
orderFill.referralFeeReceived);
}
/**
* @dev Throws when the order status is invalid or the signer is not valid.
*/
function assertTakeOrder(
bytes32 orderHash,
uint8 status,
address signer,
bytes memory signature
)
internal
pure
returns(uint8)
{
uint8 result = uint8(OrderStatus.FILLABLE);
if(recover(orderHash, signature) != signer) {
result = uint8(OrderStatus.INVALID_SIGNER);
}
if(status != uint8(OrderStatus.FILLABLE)) {
result = status;
}
return status;
}
/**
* @dev Updates the contract state i.e. user balances
*/
function executeTrade(
Order memory order,
OrderFill memory orderFill
)
private
{
uint256 makerGiveAmount = orderFill.takerFillAmount.sub(orderFill.makerFeeReceived);
uint256 takerFillAmount = orderFill.takerFillAmount.sub(orderFill.takerFeePaid);
address referrer = referrals[order.taker];
address feeAddress = feeAccount;
balances[order.makerSellToken][referrer] = balances[order.makerSellToken][referrer].add(orderFill.referralFeeReceived);
balances[order.makerSellToken][feeAddress] = balances[order.makerSellToken][feeAddress].add(orderFill.exchangeFeeReceived);
balances[order.makerBuyToken][order.taker] = balances[order.makerBuyToken][order.taker].sub(orderFill.makerFillAmount);
balances[order.makerBuyToken][order.maker] = balances[order.makerBuyToken][order.maker].add(orderFill.makerFillAmount);
balances[order.makerSellToken][order.taker] = balances[order.makerSellToken][order.taker].add(takerFillAmount);
balances[order.makerSellToken][order.maker] = balances[order.makerSellToken][order.maker].sub(makerGiveAmount);
}
}
contract ExchangeKyberProxy is Exchange, LibKyberData {
using SafeERC20 for IERC20;
/**
* @dev The precision used for calculating the amounts - 10*18
*/
uint256 constant internal PRECISION = 1000000000000000000;
/**
* @dev Max decimals allowed when calculating amounts.
*/
uint256 constant internal MAX_DECIMALS = 18;
/**
* @dev Decimals of Ether.
*/
uint256 constant internal ETH_DECIMALS = 18;
/**
* @dev The address that represents ETH in Kyber Network Contracts.
*/
address constant internal KYBER_ETH_TOKEN_ADDRESS =
address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
/**
* @dev KyberNetworkProxy contract address
*/
IKyberNetworkProxy constant internal kyberNetworkContract =
IKyberNetworkProxy(0x818E6FECD516Ecc3849DAf6845e3EC868087B755);
/**
* @dev Swaps ETH/TOKEN, TOKEN/ETH or TOKEN/TOKEN using KyberNetwork reserves.
*/
function kyberSwap(
uint256 givenAmount,
address givenToken,
address receivedToken,
bytes32 hash
)
public
payable
{
address taker = msg.sender;
KyberData memory kyberData = getSwapInfo(
givenAmount,
givenToken,
receivedToken,
taker
);
uint256 convertedAmount = kyberNetworkContract.trade.value(kyberData.value)(
kyberData.givenToken,
givenAmount,
kyberData.receivedToken,
taker,
kyberData.expectedReceiveAmount,
kyberData.rate,
feeAccount
);
emit Trade(
address(kyberNetworkContract),
taker,
hash,
givenToken,
receivedToken,
givenAmount,
convertedAmount,
0,
0,
0
);
}
/**
* @dev Exchange ETH/TOKEN, TOKEN/ETH or TOKEN/TOKEN using the internal
* balance mapping that keeps track of user's balances. It requires user to first invoke deposit function.
* The function relies on KyberNetworkProxy contract.
*/
function kyberTrade(
uint256 givenAmount,
address givenToken,
address receivedToken,
bytes32 hash
)
public
{
address taker = msg.sender;
KyberData memory kyberData = getTradeInfo(
givenAmount,
givenToken,
receivedToken
);
balances[givenToken][taker] = balances[givenToken][taker].sub(givenAmount);
uint256 convertedAmount = kyberNetworkContract.trade.value(kyberData.value)(
kyberData.givenToken,
givenAmount,
kyberData.receivedToken,
address(this),
kyberData.expectedReceiveAmount,
kyberData.rate,
feeAccount
);
balances[receivedToken][taker] = balances[receivedToken][taker].add(convertedAmount);
emit Trade(
address(kyberNetworkContract),
taker,
hash,
givenToken,
receivedToken,
givenAmount,
convertedAmount,
0,
0,
0
);
}
/**
* @dev Helper function to determine what is being swapped.
*/
function getSwapInfo(
uint256 givenAmount,
address givenToken,
address receivedToken,
address taker
)
private
returns(KyberData memory)
{
KyberData memory kyberData;
uint256 givenTokenDecimals;
uint256 receivedTokenDecimals;
if(givenToken == address(0x0)) {
require(msg.value == givenAmount, "INVALID_ETH_VALUE");
kyberData.givenToken = KYBER_ETH_TOKEN_ADDRESS;
kyberData.receivedToken = receivedToken;
kyberData.value = givenAmount;
givenTokenDecimals = ETH_DECIMALS;
receivedTokenDecimals = IERC20(receivedToken).decimals();
} else if(receivedToken == address(0x0)) {
kyberData.givenToken = givenToken;
kyberData.receivedToken = KYBER_ETH_TOKEN_ADDRESS;
kyberData.value = 0;
givenTokenDecimals = IERC20(givenToken).decimals();
receivedTokenDecimals = ETH_DECIMALS;
IERC20(givenToken).safeTransferFrom(taker, address(this), givenAmount);
IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);
} else {
kyberData.givenToken = givenToken;
kyberData.receivedToken = receivedToken;
kyberData.value = 0;
givenTokenDecimals = IERC20(givenToken).decimals();
receivedTokenDecimals = IERC20(receivedToken).decimals();
IERC20(givenToken).safeTransferFrom(taker, address(this), givenAmount);
IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);
}
(kyberData.rate, ) = kyberNetworkContract.getExpectedRate(
kyberData.givenToken,
kyberData.receivedToken,
givenAmount
);
kyberData.expectedReceiveAmount = calculateExpectedAmount(
givenAmount,
givenTokenDecimals,
receivedTokenDecimals,
kyberData.rate
);
return kyberData;
}
/**
* @dev Helper function to determines what is being
swapped using the internal balance mapping.
*/
function getTradeInfo(
uint256 givenAmount,
address givenToken,
address receivedToken
)
private
returns(KyberData memory)
{
KyberData memory kyberData;
uint256 givenTokenDecimals;
uint256 receivedTokenDecimals;
if(givenToken == address(0x0)) {
kyberData.givenToken = KYBER_ETH_TOKEN_ADDRESS;
kyberData.receivedToken = receivedToken;
kyberData.value = givenAmount;
givenTokenDecimals = ETH_DECIMALS;
receivedTokenDecimals = IERC20(receivedToken).decimals();
} else if(receivedToken == address(0x0)) {
kyberData.givenToken = givenToken;
kyberData.receivedToken = KYBER_ETH_TOKEN_ADDRESS;
kyberData.value = 0;
givenTokenDecimals = IERC20(givenToken).decimals();
receivedTokenDecimals = ETH_DECIMALS;
IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);
} else {
kyberData.givenToken = givenToken;
kyberData.receivedToken = receivedToken;
kyberData.value = 0;
givenTokenDecimals = IERC20(givenToken).decimals();
receivedTokenDecimals = IERC20(receivedToken).decimals();
IERC20(givenToken).safeApprove(address(kyberNetworkContract), givenAmount);
}
(kyberData.rate, ) = kyberNetworkContract.getExpectedRate(
kyberData.givenToken,
kyberData.receivedToken,
givenAmount
);
kyberData.expectedReceiveAmount = calculateExpectedAmount(
givenAmount,
givenTokenDecimals,
receivedTokenDecimals,
kyberData.rate
);
return kyberData;
}
function getExpectedRateBatch(
address[] memory givenTokens,
address[] memory receivedTokens,
uint256[] memory givenAmounts
)
public
view
returns(uint256[] memory, uint256[] memory)
{
uint256 size = givenTokens.length;
uint256[] memory expectedRates = new uint256[](size);
uint256[] memory slippageRates = new uint256[](size);
for(uint256 index = 0; index < size; index++) {
(expectedRates[index], slippageRates[index]) = kyberNetworkContract.getExpectedRate(
givenTokens[index],
receivedTokens[index],
givenAmounts[index]
);
}
return (expectedRates, slippageRates);
}
/**
* @dev Helper function to get the expected amount based on
* the given token and the rate from the KyberNetworkProxy
*/
function calculateExpectedAmount(
uint256 givenAmount,
uint256 givenDecimals,
uint256 receivedDecimals,
uint256 rate
)
internal
pure
returns(uint)
{
if (receivedDecimals >= givenDecimals) {
require(
(receivedDecimals - givenDecimals) <= MAX_DECIMALS,
"MAX_DECIMALS_EXCEEDED"
);
return (givenAmount * rate * (10 ** (receivedDecimals - givenDecimals)) ) / PRECISION;
} else {
require(
(givenDecimals - receivedDecimals) <= MAX_DECIMALS,
"MAX_DECIMALS_EXCEEDED"
);
return (givenAmount * rate) / (PRECISION * (10**(givenDecimals - receivedDecimals)));
}
}
}
contract ExchangeBatchTrade is Exchange {
/**
* @dev Cancel an array of orders if msg.sender is the order signer.
*/
function cancelMultipleOrders(
Order[] memory orders,
bytes[] memory signatures
)
public
{
for (uint256 index = 0; index < orders.length; index++) {
cancelSingleOrder(
orders[index],
signatures[index]
);
}
}
/**
* @dev Execute multiple trades based on the input orders and signatures.
* Note: reverts of one or more trades fail.
*/
function takeAllOrRevert(
Order[] memory orders,
bytes[] memory signatures
)
public
{
for (uint256 index = 0; index < orders.length; index++) {
bool result = _trade(orders[index], signatures[index]);
require(result, "INVALID_TAKEALL");
}
}
/**
* @dev Execute multiple trades based on the input orders and signatures.
* Note: does not revert if one or more trades fail.
*/
function takeAllPossible(
Order[] memory orders,
bytes[] memory signatures
)
public
{
for (uint256 index = 0; index < orders.length; index++) {
_trade(orders[index], signatures[index]);
}
}
}
contract ExchangeMovements is ExchangeStorage {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/**
* @dev emitted when a deposit is received
*/
event Deposit(
address indexed token,
address indexed user,
address indexed referral,
address beneficiary,
uint256 amount,
uint256 balance
);
/**
* @dev emitted when a withdraw is received
*/
event Withdraw(
address indexed token,
address indexed user,
uint256 amount,
uint256 balance
);
/**
* @dev emitted when a transfer is received
*/
event Transfer(
address indexed token,
address indexed user,
address indexed beneficiary,
uint256 amount,
uint256 userBalance,
uint256 beneficiaryBalance
);
/**
* @dev Updates the level 2 map `balances` based on the input
* Note: token address is (0x0) when the deposit is for ETH
*/
function deposit(
address token,
uint256 amount,
address beneficiary,
address referral
)
public
payable
{
uint256 value = amount;
address user = msg.sender;
if(token == address(0x0)) {
value = msg.value;
} else {
IERC20(token).safeTransferFrom(user, address(this), value);
}
balances[token][beneficiary] = balances[token][beneficiary].add(value);
if(referrals[user] == address(0x0)) {
referrals[user] = referral;
}
emit Deposit(
token,
user,
referrals[user],
beneficiary,
value,
balances[token][beneficiary]
);
}
/**
* @dev Updates the level 2 map `balances` based on the input
* Note: token address is (0x0) when the deposit is for ETH
*/
function withdraw(
address token,
uint amount
)
public
{
address payable user = msg.sender;
require(
balances[token][user] >= amount,
"INVALID_WITHDRAW"
);
balances[token][user] = balances[token][user].sub(amount);
if (token == address(0x0)) {
user.transfer(amount);
} else {
IERC20(token).safeTransfer(user, amount);
}
emit Withdraw(
token,
user,
amount,
balances[token][user]
);
}
/**
* @dev Transfer assets between two users inside the exchange. Updates the level 2 map `balances`
*/
function transfer(
address token,
address to,
uint256 amount
)
external
payable
{
address user = msg.sender;
require(
balances[token][user] >= amount,
"INVALID_TRANSFER"
);
balances[token][user] = balances[token][user].sub(amount);
balances[token][to] = balances[token][to].add(amount);
emit Transfer(
token,
user,
to,
amount,
balances[token][user],
balances[token][to]
);
}
}
contract ExchangeUpgradability is Ownable, ExchangeStorage {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/**
* @dev version of the exchange
*/
uint8 constant public VERSION = 1;
/**
* @dev the address of the upgraded exchange contract
*/
address public newExchange;
/**
* @dev flag to allow migrating to an upgraded contract
*/
bool public migrationAllowed;
/**
* @dev emitted when funds are migrated
*/
event FundsMigrated(address indexed user, address indexed newExchange);
/**
* @dev Owner can set the address of the new version of the exchange contract.
*/
function setNewExchangeAddress(address exchange)
external
onlyOwner
{
newExchange = exchange;
}
/**
* @dev Enables/Disables the migrations. Can be called only by the owner.
*/
function allowOrRestrictMigrations()
external
onlyOwner
{
migrationAllowed = !migrationAllowed;
}
/**
* @dev Migrating assets of the caller to the new exchange contract
*/
function migrateFunds(address[] calldata tokens) external {
require(
false != migrationAllowed,
"MIGRATIONS_DISALLOWED"
);
require(
IExchangeUpgradability(newExchange).VERSION() > VERSION,
"INVALID_VERSION"
);
migrateEthers();
migrateTokens(tokens);
emit FundsMigrated(msg.sender, newExchange);
}
/**
* @dev Helper function to migrate user's Ethers. Should be called in migrateFunds() function.
*/
function migrateEthers() private {
address user = msg.sender;
uint256 etherAmount = balances[address(0x0)][user];
if (etherAmount > 0) {
balances[address(0x0)][user] = 0;
IExchangeUpgradability(newExchange).importEthers.value(etherAmount)(user);
}
}
/**
* @dev Helper function to migrate user's tokens. Should be called in migrateFunds() function.
*/
function migrateTokens(address[] memory tokens) private {
address user = msg.sender;
address exchange = newExchange;
for (uint256 index = 0; index < tokens.length; index++) {
address tokenAddress = tokens[index];
uint256 tokenAmount = balances[tokenAddress][user];
if (0 == tokenAmount) {
continue;
}
IERC20(tokenAddress).safeApprove(exchange, tokenAmount);
balances[tokenAddress][user] = 0;
IExchangeUpgradability(exchange).importTokens(tokenAddress, tokenAmount, user);
}
}
/**
* @dev Helper function to migrate user's Ethers. Should be called only from the new exchange contract.
*/
function importEthers(address user)
external
payable
{
require(
false != migrationAllowed,
"MIGRATION_DISALLOWED"
);
require(
user != address(0x0),
"INVALID_USER"
);
require(
msg.value > 0,
"INVALID_AMOUNT"
);
require(
IExchangeUpgradability(msg.sender).VERSION() < VERSION,
"INVALID_VERSION"
);
balances[address(0x0)][user] = balances[address(0x0)][user].add(msg.value); // todo: constants
}
/**
* @dev Helper function to migrate user's Tokens. Should be called only from the new exchange contract.
*/
function importTokens(
address token,
uint256 amount,
address user
)
external
{
require(
false != migrationAllowed,
"MIGRATION_DISALLOWED"
);
require(
token != address(0x0),
"INVALID_TOKEN"
);
require(
user != address(0x0),
"INVALID_USER"
);
require(
amount > 0,
"INVALID_AMOUNT"
);
require(
IExchangeUpgradability(msg.sender).VERSION() < VERSION,
"INVALID_VERSION"
);
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
balances[token][user] = balances[token][user].add(amount);
}
}
contract ExchangeOffering is ExchangeStorage, LibCrowdsale {
address constant internal BURN_ADDRESS = address(0x000000000000000000000000000000000000dEaD);
address constant internal ETH_ADDRESS = address(0x0);
using SafeERC20 for IERC20;
using SafeMath for uint256;
mapping(address => Crowdsale) public crowdsales;
mapping(address => mapping(address => uint256)) public contributions;
event TokenPurchase(
address indexed token,
address indexed user,
uint256 tokenAmount,
uint256 weiAmount
);
event TokenBurned(
address indexed token,
uint256 tokenAmount
);
function registerCrowdsale(
Crowdsale memory crowdsale,
address token
)
public
onlyOwner
{
require(
CrowdsaleStatus.VALID == getCrowdsaleStatus(crowdsale),
"INVALID_CROWDSALE"
);
require(
crowdsales[token].wallet == address(0),
"CROWDSALE_ALREADY_EXISTS"
);
uint256 tokenForSale = crowdsale.hardCap.mul(crowdsale.tokenRatio);
IERC20(token).safeTransferFrom(crowdsale.wallet, address(this), tokenForSale);
crowdsales[token] = crowdsale;
}
function buyTokens(address token)
public
payable
{
require(msg.value != 0, "INVALID_MSG_VALUE");
uint256 weiAmount = msg.value;
address user = msg.sender;
Crowdsale memory crowdsale = crowdsales[token];
require(
ContributionStatus.VALID == validContribution(weiAmount, crowdsale, user, token),
"INVALID_CONTRIBUTION"
);
uint256 purchasedTokens = weiAmount.mul(crowdsale.tokenRatio);
crowdsale.leftAmount = crowdsale.leftAmount.sub(purchasedTokens);
crowdsale.weiRaised = crowdsale.weiRaised.add(weiAmount);
balances[ETH_ADDRESS][crowdsale.wallet] = balances[ETH_ADDRESS][crowdsale.wallet].add(weiAmount);
balances[token][user] = balances[token][user].add(purchasedTokens);
contributions[token][user] = contributions[token][user].add(weiAmount);
crowdsales[token] = crowdsale;
emit TokenPurchase(token, user, purchasedTokens, weiAmount);
}
function burnTokensWhenFinished(address token) public
{
require(
isFinished(crowdsales[token].endBlock),
"CROWDSALE_NOT_FINISHED_YET"
);
uint256 leftAmount = crowdsales[token].leftAmount;
crowdsales[token].leftAmount = 0;
IERC20(token).safeTransfer(BURN_ADDRESS, leftAmount);
emit TokenBurned(token, leftAmount);
}
function validContribution(
uint256 weiAmount,
Crowdsale memory crowdsale,
address user,
address token
)
public
view
returns(ContributionStatus)
{
if (!isOpened(crowdsale.startBlock, crowdsale.endBlock)) {
return ContributionStatus.CROWDSALE_NOT_OPEN;
}
if(weiAmount < crowdsale.minContribution) {
return ContributionStatus.MIN_CONTRIBUTION;
}
if (contributions[token][user].add(weiAmount) > crowdsale.maxContribution) {
return ContributionStatus.MAX_CONTRIBUTION;
}
if (crowdsale.hardCap < crowdsale.weiRaised.add(weiAmount)) {
return ContributionStatus.HARDCAP_REACHED;
}
return ContributionStatus.VALID;
}
}
contract ExchangeSwap is Exchange, ExchangeMovements {
/**
* @dev Swaps ETH/TOKEN, TOKEN/ETH or TOKEN/TOKEN using off-chain signed messages.
* The flow of the function is Deposit -> Trade -> Withdraw to allow users to directly
* take liquidity without the need of deposit and withdraw.
*/
function swapFill(
Order[] memory orders,
bytes[] memory signatures,
uint256 givenAmount,
address givenToken,
address receivedToken,
address referral
)
public
payable
{
address taker = msg.sender;
uint256 balanceGivenBefore = balances[givenToken][taker];
uint256 balanceReceivedBefore = balances[receivedToken][taker];
deposit(givenToken, givenAmount, taker, referral);
for (uint256 index = 0; index < orders.length; index++) {
require(orders[index].makerBuyToken == givenToken, "GIVEN_TOKEN");
require(orders[index].makerSellToken == receivedToken, "RECEIVED_TOKEN");
_trade(orders[index], signatures[index]);
}
uint256 balanceGivenAfter = balances[givenToken][taker];
uint256 balanceReceivedAfter = balances[receivedToken][taker];
uint256 balanceGivenDelta = balanceGivenAfter.sub(balanceGivenBefore);
uint256 balanceReceivedDelta = balanceReceivedAfter.sub(balanceReceivedBefore);
if(balanceGivenDelta > 0) {
withdraw(givenToken, balanceGivenDelta);
}
if(balanceReceivedDelta > 0) {
withdraw(receivedToken, balanceReceivedDelta);
}
}
}
contract WeiDex is
Exchange,
ExchangeKyberProxy,
ExchangeBatchTrade,
ExchangeMovements,
ExchangeUpgradability,
ExchangeOffering,
ExchangeSwap
{
function () external payable { }
} | * @return return array of true(false) if orders specified by `orderHash` array are(not) cancelled/ | function getCancels(
bytes32[] memory orderHash
)
public
view
returns (bool[]memory cancelledArray)
{
cancelledArray = new bool[](orderHash.length);
for(uint256 index = 0; index < orderHash.length; index++) {
cancelledArray[index] = cancelled[orderHash[index]];
}
}
| 5,365,835 | [
1,
2463,
327,
526,
434,
638,
12,
5743,
13,
309,
11077,
1269,
635,
1375,
1019,
2310,
68,
526,
854,
12,
902,
13,
13927,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
12006,
2183,
87,
12,
203,
3639,
1731,
1578,
8526,
3778,
1353,
2310,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
8526,
7858,
13927,
1076,
13,
203,
565,
288,
203,
3639,
13927,
1076,
273,
394,
1426,
8526,
12,
1019,
2310,
18,
2469,
1769,
203,
203,
3639,
364,
12,
11890,
5034,
770,
273,
374,
31,
770,
411,
1353,
2310,
18,
2469,
31,
770,
27245,
288,
203,
5411,
13927,
1076,
63,
1615,
65,
273,
13927,
63,
1019,
2310,
63,
1615,
13563,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x5D01d44fC4A028a8FAb9cB49cc161A20727F985F/sources/UMB.sol | @title Umbrella Rewards contract @author umb.network @notice This contract allows to mint tokens and burn key (renounceOwnership) @dev Can be use used with MultiSig as owner ========== STATE VARIABLES ========== ========== CONSTRUCTOR ========== | abstract contract MintableToken is Owned, ERC20, IBurnableToken {
using SafeMath for uint256;
uint256 public maxAllowedTotalSupply;
constructor (uint256 _maxAllowedTotalSupply) {
require(_maxAllowedTotalSupply != 0, "_maxAllowedTotalSupply is empty");
maxAllowedTotalSupply = _maxAllowedTotalSupply;
}
modifier assertMaxSupply(uint256 _amountToMint) {
require(totalSupply().add(_amountToMint) <= maxAllowedTotalSupply, "total supply limit exceeded");
_;
}
function burn(uint256 _amount) override external {
uint balance = balanceOf(msg.sender);
require(_amount <= balance, "not enough tokens to burn");
_burn(msg.sender, balance);
maxAllowedTotalSupply = maxAllowedTotalSupply - balance;
}
function mint(address _holder, uint256 _amount)
external
onlyOwner()
assertMaxSupply(_amount) {
require(_amount > 0, "zero amount");
_mint(_holder, _amount);
}
}
| 9,107,227 | [
1,
57,
1627,
2878,
11821,
534,
359,
14727,
6835,
282,
225,
3592,
18,
5185,
282,
1220,
6835,
5360,
358,
312,
474,
2430,
471,
18305,
498,
261,
1187,
8386,
5460,
12565,
13,
1377,
4480,
506,
999,
1399,
598,
5991,
8267,
487,
3410,
422,
1432,
7442,
22965,
55,
422,
1432,
225,
422,
1432,
3492,
13915,
916,
422,
1432,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
490,
474,
429,
1345,
353,
14223,
11748,
16,
4232,
39,
3462,
16,
23450,
321,
429,
1345,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
203,
225,
2254,
5034,
1071,
943,
5042,
5269,
3088,
1283,
31,
203,
203,
203,
203,
203,
225,
3885,
261,
11890,
5034,
389,
1896,
5042,
5269,
3088,
1283,
13,
288,
203,
565,
2583,
24899,
1896,
5042,
5269,
3088,
1283,
480,
374,
16,
4192,
1896,
5042,
5269,
3088,
1283,
353,
1008,
8863,
203,
565,
943,
5042,
5269,
3088,
1283,
273,
389,
1896,
5042,
5269,
3088,
1283,
31,
203,
225,
289,
203,
203,
203,
225,
9606,
1815,
2747,
3088,
1283,
12,
11890,
5034,
389,
8949,
774,
49,
474,
13,
288,
203,
565,
2583,
12,
4963,
3088,
1283,
7675,
1289,
24899,
8949,
774,
49,
474,
13,
1648,
943,
5042,
5269,
3088,
1283,
16,
315,
4963,
14467,
1800,
12428,
8863,
203,
565,
389,
31,
203,
225,
289,
203,
203,
203,
225,
445,
18305,
12,
11890,
5034,
389,
8949,
13,
3849,
3903,
288,
203,
565,
2254,
11013,
273,
11013,
951,
12,
3576,
18,
15330,
1769,
203,
565,
2583,
24899,
8949,
1648,
11013,
16,
315,
902,
7304,
2430,
358,
18305,
8863,
203,
203,
565,
389,
70,
321,
12,
3576,
18,
15330,
16,
11013,
1769,
203,
565,
943,
5042,
5269,
3088,
1283,
273,
943,
5042,
5269,
3088,
1283,
300,
11013,
31,
203,
225,
289,
203,
203,
203,
225,
445,
312,
474,
12,
2867,
389,
4505,
16,
2254,
5034,
389,
8949,
13,
203,
225,
3903,
203,
225,
1338,
5541,
1435,
203,
225,
1815,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-04
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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);
}
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;
}
}
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);
}
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity 0.6.12;
// Chip with Governance.
contract Chip is ERC20("Chip", "CHIP"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function airdrop(address[] memory addresses, uint256[] memory amounts) public onlyOwner returns (bool) {
require(addresses.length > 0 && addresses.length == amounts.length);
uint256 totalAmount = 0;
for(uint j = 0; j < addresses.length; j++){
require(amounts[j] > 0 && addresses[j] != address(0));
totalAmount = totalAmount.add(amounts[j]);
}
require(balanceOf(msg.sender) >= totalAmount);
for (uint j = 0; j < addresses.length; j++) {
transfer(addresses[j], amounts[j]);
}
return true;
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH,delegatee,nonce,expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01",domainSeparator,structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CHIP::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CHIP::delegateBySig: invalid nonce");
require(now <= expiry, "CHIP::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "CHIP::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying CHIPs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "CHIP::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | @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) {
return msg.data;
}
}
| 7,815,815 | [
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,
611,
13653,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
17801,
6835,
1772,
288,
6862,
6862,
6862,
6862,
6862,
25083,
203,
203,
6862,
6862,
6862,
6862,
6862,
25083,
203,
915,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
8843,
429,
13,
288,
6862,
6862,
6862,
6862,
6862,
25083,
203,
2463,
1234,
18,
15330,
31,
6862,
6862,
6862,
6862,
6862,
25083,
203,
97,
6862,
6862,
6862,
6862,
6862,
25083,
203,
6862,
6862,
6862,
6862,
6862,
25083,
203,
915,
389,
3576,
751,
1435,
2713,
1476,
5024,
1135,
261,
3890,
3778,
13,
288,
6862,
6862,
6862,
6862,
6862,
25083,
203,
2463,
1234,
18,
892,
31,
6862,
6862,
6862,
6862,
6862,
25083,
203,
97,
6862,
6862,
6862,
6862,
6862,
25083,
203,
97,
6862,
6862,
6862,
6862,
6862,
25083,
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
] |
pragma solidity 0.5.8;
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\IERC20.sol
interface IERC20 {
function TOTALSUPPLY82() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF530(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER438(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE833(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE538(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM818(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER722(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL422(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: node_modules\openzeppelin-solidity\contracts\math\SafeMath.sol
library SafeMath {
function ADD23(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB764(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function MUL177(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV24(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD404(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: node_modules\openzeppelin-solidity\contracts\token\ERC20\ERC20.sol
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY82() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF530(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER438(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER27(msg.sender, recipient, amount);
return true;
}
function ALLOWANCE833(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE538(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, value);
return true;
}
function TRANSFERFROM818(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER27(sender, recipient, amount);
_APPROVE258(sender, msg.sender, _allowances[sender][msg.sender].SUB764(amount));
return true;
}
function INCREASEALLOWANCE45(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, _allowances[msg.sender][spender].ADD23(addedValue));
return true;
}
function DECREASEALLOWANCE159(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE258(msg.sender, spender, _allowances[msg.sender][spender].SUB764(subtractedValue));
return true;
}
function _TRANSFER27(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB764(amount);
_balances[recipient] = _balances[recipient].ADD23(amount);
emit TRANSFER722(sender, recipient, amount);
}
function _MINT102(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD23(amount);
_balances[account] = _balances[account].ADD23(amount);
emit TRANSFER722(address(0), account, amount);
}
function _BURN692(address account, uint256 value) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.SUB764(value);
_balances[account] = _balances[account].SUB764(value);
emit TRANSFER722(account, address(0), value);
}
function _APPROVE258(address owner, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit APPROVAL422(owner, spender, value);
}
function _BURNFROM631(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN692(account, amount);
_APPROVE258(account, msg.sender, _allowances[account][msg.sender].SUB764(amount));
}
}
// File: J\contracts\Goodluck(LUCK).sol
contract Goodluck is ERC20 {
string public constant name423 = "Goodluck"; //inject NONSTANDARD NAMING
string public constant symbol470 = "LUCK"; //inject NONSTANDARD NAMING
uint8 public constant decimals728 = 18; //inject NONSTANDARD NAMING
uint256 public constant initialsupply595 = 2000000000 * (10 ** uint256(decimals728)); //inject NONSTANDARD NAMING
constructor() public {
super._MINT102(msg.sender, initialsupply595);
owner = msg.sender;
}
//ownership
address public owner;
event OWNERSHIPRENOUNCED774(address indexed previousOwner); //inject NONSTANDARD NAMING
event OWNERSHIPTRANSFERRED463( //inject NONSTANDARD NAMING
address indexed previousOwner,
address indexed newOwner
);
modifier ONLYOWNER394() { //inject NONSTANDARD NAMING
require(msg.sender == owner, "Not owner");
_;
}
function RENOUNCEOWNERSHIP445() public ONLYOWNER394 { //inject NONSTANDARD NAMING
emit OWNERSHIPRENOUNCED774(owner);
owner = address(0);
}
function TRANSFEROWNERSHIP781(address _newOwner) public ONLYOWNER394 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP16(_newOwner);
}
function _TRANSFEROWNERSHIP16(address _newOwner) internal { //inject NONSTANDARD NAMING
require(_newOwner != address(0), "Already owner");
emit OWNERSHIPTRANSFERRED463(owner, _newOwner);
owner = _newOwner;
}
//pausable
event PAUSE475(); //inject NONSTANDARD NAMING
event UNPAUSE568(); //inject NONSTANDARD NAMING
bool public paused = false;
modifier WHENNOTPAUSED995() { //inject NONSTANDARD NAMING
require(!paused, "Paused by owner");
_;
}
modifier WHENPAUSED712() { //inject NONSTANDARD NAMING
require(paused, "Not paused now");
_;
}
function PAUSE841() public ONLYOWNER394 WHENNOTPAUSED995 { //inject NONSTANDARD NAMING
paused = true;
emit PAUSE475();
}
function UNPAUSE13() public ONLYOWNER394 WHENPAUSED712 { //inject NONSTANDARD NAMING
paused = false;
emit UNPAUSE568();
}
//freezable
event FROZEN932(address target); //inject NONSTANDARD NAMING
event UNFROZEN285(address target); //inject NONSTANDARD NAMING
mapping(address => bool) internal freezes;
modifier WHENNOTFROZEN284() { //inject NONSTANDARD NAMING
require(!freezes[msg.sender], "Sender account is locked.");
_;
}
function FREEZE724(address _target) public ONLYOWNER394 { //inject NONSTANDARD NAMING
freezes[_target] = true;
emit FROZEN932(_target);
}
function UNFREEZE196(address _target) public ONLYOWNER394 { //inject NONSTANDARD NAMING
freezes[_target] = false;
emit UNFROZEN285(_target);
}
function ISFROZEN713(address _target) public view returns (bool) { //inject NONSTANDARD NAMING
return freezes[_target];
}
function TRANSFER438( //inject NONSTANDARD NAMING
address _to,
uint256 _value
)
public
WHENNOTFROZEN284
WHENNOTPAUSED995
returns (bool)
{
RELEASELOCK766(msg.sender);
return super.TRANSFER438(_to, _value);
}
function TRANSFERFROM818( //inject NONSTANDARD NAMING
address _from,
address _to,
uint256 _value
)
public
WHENNOTPAUSED995
returns (bool)
{
require(!freezes[_from], "From account is locked.");
RELEASELOCK766(_from);
return super.TRANSFERFROM818(_from, _to, _value);
}
//mintable
event MINT926(address indexed to, uint256 amount); //inject NONSTANDARD NAMING
function MINT957( //inject NONSTANDARD NAMING
address _to,
uint256 _amount
)
public
ONLYOWNER394
returns (bool)
{
super._MINT102(_to, _amount);
emit MINT926(_to, _amount);
return true;
}
//burnable
event BURN684(address indexed burner, uint256 value); //inject NONSTANDARD NAMING
function BURN342(address _who, uint256 _value) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(_value <= super.BALANCEOF530(_who), "Balance is too small.");
_BURN692(_who, _value);
emit BURN684(_who, _value);
}
//lockable
struct LockInfo {
uint256 releaseTime;
uint256 balance;
}
mapping(address => LockInfo[]) internal lockInfo;
event LOCK205(address indexed holder, uint256 value, uint256 releaseTime); //inject NONSTANDARD NAMING
event UNLOCK375(address indexed holder, uint256 value); //inject NONSTANDARD NAMING
function BALANCEOF530(address _holder) public view returns (uint256 balance) { //inject NONSTANDARD NAMING
uint256 lockedBalance = 0;
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
lockedBalance = lockedBalance.ADD23(lockInfo[_holder][i].balance);
}
return super.BALANCEOF530(_holder).ADD23(lockedBalance);
}
function RELEASELOCK766(address _holder) internal { //inject NONSTANDARD NAMING
for(uint256 i = 0; i < lockInfo[_holder].length ; i++ ) {
if (lockInfo[_holder][i].releaseTime <= now) {
_balances[_holder] = _balances[_holder].ADD23(lockInfo[_holder][i].balance);
emit UNLOCK375(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
i--;
}
lockInfo[_holder].length--;
}
}
}
function LOCKCOUNT904(address _holder) public view returns (uint256) { //inject NONSTANDARD NAMING
return lockInfo[_holder].length;
}
function LOCKSTATE154(address _holder, uint256 _idx) public view returns (uint256, uint256) { //inject NONSTANDARD NAMING
return (lockInfo[_holder][_idx].releaseTime, lockInfo[_holder][_idx].balance);
}
function LOCK109(address _holder, uint256 _amount, uint256 _releaseTime) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(super.BALANCEOF530(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].SUB764(_amount);
lockInfo[_holder].push(
LockInfo(_releaseTime, _amount)
);
emit LOCK205(_holder, _amount, _releaseTime);
}
function LOCKAFTER210(address _holder, uint256 _amount, uint256 _afterTime) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(super.BALANCEOF530(_holder) >= _amount, "Balance is too small.");
_balances[_holder] = _balances[_holder].SUB764(_amount);
lockInfo[_holder].push(
LockInfo(now + _afterTime, _amount)
);
emit LOCK205(_holder, _amount, now + _afterTime);
}
function UNLOCK592(address _holder, uint256 i) public ONLYOWNER394 { //inject NONSTANDARD NAMING
require(i < lockInfo[_holder].length, "No lock information.");
_balances[_holder] = _balances[_holder].ADD23(lockInfo[_holder][i].balance);
emit UNLOCK375(_holder, lockInfo[_holder][i].balance);
lockInfo[_holder][i].balance = 0;
if (i != lockInfo[_holder].length - 1) {
lockInfo[_holder][i] = lockInfo[_holder][lockInfo[_holder].length - 1];
}
lockInfo[_holder].length--;
}
function TRANSFERWITHLOCK415(address _to, uint256 _value, uint256 _releaseTime) public ONLYOWNER394 returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0), "wrong address");
require(_value <= super.BALANCEOF530(owner), "Not enough balance");
_balances[owner] = _balances[owner].SUB764(_value);
lockInfo[_to].push(
LockInfo(_releaseTime, _value)
);
emit TRANSFER722(owner, _to, _value);
emit LOCK205(_to, _value, _releaseTime);
return true;
}
function TRANSFERWITHLOCKAFTER686(address _to, uint256 _value, uint256 _afterTime) public ONLYOWNER394 returns (bool) { //inject NONSTANDARD NAMING
require(_to != address(0), "wrong address");
require(_value <= super.BALANCEOF530(owner), "Not enough balance");
_balances[owner] = _balances[owner].SUB764(_value);
lockInfo[_to].push(
LockInfo(now + _afterTime, _value)
);
emit TRANSFER722(owner, _to, _value);
emit LOCK205(_to, _value, now + _afterTime);
return true;
}
function CURRENTTIME149() public view returns (uint256) { //inject NONSTANDARD NAMING
return now;
}
function AFTERTIME613(uint256 _value) public view returns (uint256) { //inject NONSTANDARD NAMING
return now + _value;
}
//airdrop
mapping (address => uint256) public airDropHistory;
event AIRDROP940(address _receiver, uint256 _amount); //inject NONSTANDARD NAMING
function DROPTOKEN612(address[] memory receivers, uint256[] memory values) ONLYOWNER394 public { //inject NONSTANDARD NAMING
require(receivers.length != 0);
require(receivers.length == values.length);
for (uint256 i = 0; i < receivers.length; i++) {
address receiver = receivers[i];
uint256 amount = values[i];
TRANSFER438(receiver, amount);
airDropHistory[receiver] += amount;
emit AIRDROP940(receiver, amount);
}
}
} | inject NONSTANDARD NAMING
| event OWNERSHIPRENOUNCED774(address indexed previousOwner); | 12,758,974 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
871,
531,
22527,
20101,
862,
3417,
2124,
23552,
4700,
24,
12,
2867,
8808,
2416,
5541,
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
] |
./full_match/4/0x7Bd6062a2056Ba6b9775EfF89fdAa507Ba4B9E14/sources/baal.sol | @notice Interface for Baal {memberAction} that adjusts member `shares` & `loot`. | interface IShaman {
function memberAction(
address member,
uint96 loot,
uint96 shares
) external payable returns (uint96 lootOut, uint96 sharesOut);
}
| 12,297,267 | [
1,
1358,
364,
605,
69,
287,
288,
5990,
1803,
97,
716,
5765,
87,
3140,
1375,
30720,
68,
473,
1375,
383,
352,
8338,
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,
5831,
467,
1555,
301,
304,
288,
203,
565,
445,
3140,
1803,
12,
203,
3639,
1758,
3140,
16,
203,
3639,
2254,
10525,
437,
352,
16,
203,
3639,
2254,
10525,
24123,
203,
565,
262,
3903,
8843,
429,
1135,
261,
11890,
10525,
437,
352,
1182,
16,
2254,
10525,
24123,
1182,
1769,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xefaCa6Fc316B3B2Aa6c55FF5E02a62A85d4391e8/sources/@synthetixio/core-contracts/contracts/token/ERC721.sol | * @inheritdoc IERC721Metadata/ | function name() external view virtual override returns (string memory) {
return ERC721Storage.load().name;
}
| 16,517,429 | [
1,
36,
10093,
467,
654,
39,
27,
5340,
2277,
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,
508,
1435,
3903,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
327,
4232,
39,
27,
5340,
3245,
18,
945,
7675,
529,
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
] |
./partial_match/42220/0x1EC3366D384ee7996F2F70B67A65C5d54Ce96040/sources/home/eruiz/Projects/celo/celo-monorepo/packages/protocol/contracts/identity/Attestations.sol | * @notice Returns the storage, major, minor, and patch version of the contract. @return The storage, major, minor, and patch version of the contract./ | function getVersionNumber() external pure returns (uint256, uint256, uint256, uint256) {
return (1, 1, 1, 2);
}
| 3,499,731 | [
1,
1356,
326,
2502,
16,
7888,
16,
8439,
16,
471,
4729,
1177,
434,
326,
6835,
18,
327,
1021,
2502,
16,
7888,
16,
8439,
16,
471,
4729,
1177,
434,
326,
6835,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
8343,
1854,
1435,
3903,
16618,
1135,
261,
11890,
5034,
16,
2254,
5034,
16,
2254,
5034,
16,
2254,
5034,
13,
288,
203,
565,
327,
261,
21,
16,
404,
16,
404,
16,
576,
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,
-100
] |
./partial_match/56/0xF5143860aB973f08d359CcFCd7bF3cB6F86B7042/sources/Cocaine.sol | * @dev Moves tokens `amount` from `sender` to `recipient`. This is internal function is equivalent to {transfer}, and can be used to e.g. implement automatic token fees, slashing mechanisms, etc. Emits a {Transfer} event. Requirements: - `sender` cannot be the zero address. - `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`./ | function _transfer (address sender, address recipient, uint256 amount) internal {
require(sender != address(0), 'BEP20: transfer from the zero address');
require(recipient != address(0), 'BEP20: transfer to the zero address');
_balances[sender] = _balances[sender].YADD(amount, 'BEP20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 11,119,767 | [
1,
19297,
2430,
1375,
8949,
68,
628,
1375,
15330,
68,
358,
1375,
20367,
8338,
1220,
353,
2713,
445,
353,
7680,
358,
288,
13866,
5779,
471,
848,
506,
1399,
358,
425,
18,
75,
18,
2348,
5859,
1147,
1656,
281,
16,
9026,
310,
1791,
28757,
16,
5527,
18,
7377,
1282,
279,
288,
5912,
97,
871,
18,
29076,
30,
300,
1375,
15330,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
389,
13866,
261,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
3639,
2583,
12,
15330,
480,
1758,
12,
20,
3631,
296,
5948,
52,
3462,
30,
7412,
628,
326,
3634,
1758,
8284,
203,
3639,
2583,
12,
20367,
480,
1758,
12,
20,
3631,
296,
5948,
52,
3462,
30,
7412,
358,
326,
3634,
1758,
8284,
203,
203,
3639,
389,
70,
26488,
63,
15330,
65,
273,
389,
70,
26488,
63,
15330,
8009,
61,
8355,
12,
8949,
16,
296,
5948,
52,
3462,
30,
7412,
3844,
14399,
11013,
8284,
203,
3639,
389,
70,
26488,
63,
20367,
65,
273,
389,
70,
26488,
63,
20367,
8009,
1289,
12,
8949,
1769,
203,
3639,
3626,
12279,
12,
15330,
16,
8027,
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
] |
./partial_match/3/0xDf87bABA2A1b41455457200320e09634DC9D544E/sources/YFEED.sol | ---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ---------------------------------------------------------------------------- ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | contract YFEED is IERC20, Owned {
using SafeMath for uint256;
string public symbol = "YFEED";
string public name = "YFEED FINANCE";
uint256 public decimals = 18;
address airdropContract;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
constructor(address icoContract, address _airdropContract) public {
airdropContract = _airdropContract;
owner = 0x62f8bD7a8C5515Ca00501A3BBE35590Ab45B6bb9;
emit Transfer(address(0), icoContract, 150000 * 10 ** (18));
emit Transfer(address(0), address(owner), 150000 * 10 ** (18));
emit Transfer(address(0), address(airdropContract), 150000 * 10 ** (18));
}
function totalSupply() external override view returns (uint256){
return _totalSupply;
}
function balanceOf(address tokenOwner) external override view returns (uint256 balance) {
return balances[tokenOwner];
}
function approve(address spender, uint256 tokens) external override returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender,spender,tokens);
return true;
}
function allowance(address tokenOwner, address spender) external override view returns (uint256 remaining) {
return allowed[tokenOwner][spender];
}
function transfer(address to, uint256 tokens) public override returns (bool success) {
require(address(to) != address(0));
require(balances[msg.sender] >= tokens );
require(balances[to] + tokens >= balances[to]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
uint256 deduction = deductionsToApply(tokens);
applyDeductions(deduction);
balances[to] = balances[to].add(tokens.sub(deduction));
emit Transfer(msg.sender, to, tokens.sub(deduction));
return true;
}
function transferFrom(address from, address to, uint256 tokens) external override returns (bool success){
require(balances[from] >= tokens);
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
uint256 deduction = deductionsToApply(tokens);
applyDeductions(deduction);
balances[to] = balances[to].add(tokens.sub(deduction));
emit Transfer(from, to, tokens.sub(tokens));
return true;
}
function _transfer(address to, uint256 tokens, bool rewards) internal returns(bool){
require(address(to) != address(0));
require(balances[address(this)] >= tokens );
require(balances[to] + tokens >= balances[to]);
balances[address(this)] = balances[address(this)].sub(tokens);
uint256 deduction = 0;
if(!rewards){
deduction = deductionsToApply(tokens);
applyDeductions(deduction);
}
balances[to] = balances[to].add(tokens.sub(deduction));
emit Transfer(address(this),to,tokens.sub(deduction));
return true;
}
function _transfer(address to, uint256 tokens, bool rewards) internal returns(bool){
require(address(to) != address(0));
require(balances[address(this)] >= tokens );
require(balances[to] + tokens >= balances[to]);
balances[address(this)] = balances[address(this)].sub(tokens);
uint256 deduction = 0;
if(!rewards){
deduction = deductionsToApply(tokens);
applyDeductions(deduction);
}
balances[to] = balances[to].add(tokens.sub(deduction));
emit Transfer(address(this),to,tokens.sub(deduction));
return true;
}
function deductionsToApply(uint256 tokens) private view returns(uint256){
uint256 deduction = 0;
uint256 minSupply = 100000 * 10 ** (18);
if(_totalSupply > minSupply && msg.sender != airdropContract){
if(_totalSupply.sub(deduction) < minSupply)
deduction = _totalSupply.sub(minSupply);
}
return deduction;
}
function deductionsToApply(uint256 tokens) private view returns(uint256){
uint256 deduction = 0;
uint256 minSupply = 100000 * 10 ** (18);
if(_totalSupply > minSupply && msg.sender != airdropContract){
if(_totalSupply.sub(deduction) < minSupply)
deduction = _totalSupply.sub(minSupply);
}
return deduction;
}
function applyDeductions(uint256 deduction) private{
if(stakedCoins == 0){
burnTokens(deduction);
}
else{
burnTokens(deduction.div(2));
disburse(deduction.div(2));
}
}
function applyDeductions(uint256 deduction) private{
if(stakedCoins == 0){
burnTokens(deduction);
}
else{
burnTokens(deduction.div(2));
disburse(deduction.div(2));
}
}
function applyDeductions(uint256 deduction) private{
if(stakedCoins == 0){
burnTokens(deduction);
}
else{
burnTokens(deduction.div(2));
disburse(deduction.div(2));
}
}
function burnTokens(uint256 value) internal{
_totalSupply = _totalSupply.sub(value);
emit Transfer(msg.sender, address(0), value);
}
function onePercent(uint256 _tokens) internal pure returns (uint256){
uint256 roundValue = _tokens.ceil(100);
uint onePercentofTokens = roundValue.mul(100).div(100 * 10**uint(2));
return onePercentofTokens;
}
uint256 deployTime;
uint256 private totalDividentPoints;
uint256 private unclaimedDividendPoints;
uint256 pointMultiplier = 1000000000000000000;
uint256 public stakedCoins;
uint256 public totalRewardsClaimed;
bool public stakingOpen;
struct Account {
uint256 balance;
uint256 lastDividentPoints;
uint256 timeInvest;
uint256 lastClaimed;
uint256 rewardsClaimed;
uint256 pending;
}
mapping(address => Account) accounts;
function openStaking() external onlyOwner{
require(!stakingOpen, "staking already open");
stakingOpen = true;
}
function STAKE(uint256 _tokens) external returns(bool){
require(stakingOpen, "staking is close");
require(transfer(address(this), _tokens), "In sufficient tokens in user wallet");
uint256 owing = dividendsOwing(msg.sender);
accounts[msg.sender].pending = owing;
addToStake(_tokens);
return true;
}
function addToStake(uint256 _tokens) private{
uint256 deduction = deductionsToApply(_tokens);
accounts[msg.sender].timeInvest = now;
stakedCoins = stakedCoins.add(_tokens.sub(deduction));
accounts[msg.sender].balance = accounts[msg.sender].balance.add(_tokens.sub(deduction));
accounts[msg.sender].lastDividentPoints = totalDividentPoints;
accounts[msg.sender].lastClaimed = now;
}
function stakingStartedAt(address user) external view returns(uint256){
return accounts[user].timeInvest;
}
function pendingReward(address _user) external view returns(uint256){
uint256 owing = dividendsOwing(_user);
return owing;
}
function dividendsOwing(address investor) internal view returns (uint256){
uint256 newDividendPoints = totalDividentPoints.sub(accounts[investor].lastDividentPoints);
return (((accounts[investor].balance).mul(newDividendPoints)).div(pointMultiplier)).add(accounts[investor].pending);
}
function updateDividend(address investor) internal returns(uint256){
uint256 owing = dividendsOwing(investor);
if (owing > 0){
unclaimedDividendPoints = unclaimedDividendPoints.sub(owing);
accounts[investor].lastDividentPoints = totalDividentPoints;
accounts[investor].pending = 0;
}
return owing;
}
function updateDividend(address investor) internal returns(uint256){
uint256 owing = dividendsOwing(investor);
if (owing > 0){
unclaimedDividendPoints = unclaimedDividendPoints.sub(owing);
accounts[investor].lastDividentPoints = totalDividentPoints;
accounts[investor].pending = 0;
}
return owing;
}
function activeStake(address _user) external view returns (uint256){
return accounts[_user].balance;
}
function UNSTAKE(uint256 tokens) external returns (bool){
require(accounts[msg.sender].balance > 0);
uint256 owing = updateDividend(msg.sender);
accounts[msg.sender].pending = owing;
stakedCoins = stakedCoins.sub(tokens);
require(_transfer(msg.sender, tokens, false));
accounts[msg.sender].balance = accounts[msg.sender].balance.sub(tokens);
return true;
}
function disburse(uint256 amount) internal{
balances[address(this)] = balances[address(this)].add(amount);
uint256 unnormalized = amount.mul(pointMultiplier);
totalDividentPoints = totalDividentPoints.add(unnormalized.div(stakedCoins));
unclaimedDividendPoints = unclaimedDividendPoints.add(amount);
}
function claimReward() external returns(bool){
uint256 owing = updateDividend(msg.sender);
require(owing > 0);
require(_transfer(msg.sender, owing, true));
accounts[msg.sender].rewardsClaimed = accounts[msg.sender].rewardsClaimed.add(owing);
totalRewardsClaimed = totalRewardsClaimed.add(owing);
return true;
}
function rewardsClaimed(address _user) external view returns(uint256 rewardClaimed){
return accounts[_user].rewardsClaimed;
}
function reinvest() external {
uint256 owing = updateDividend(msg.sender);
require(owing > 0);
addToStake(owing);
}
} | 16,628,982 | [
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,
1624,
29195,
353,
467,
654,
39,
3462,
16,
14223,
11748,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
27699,
565,
533,
1071,
3273,
273,
315,
61,
29195,
14432,
203,
565,
533,
1071,
225,
508,
273,
315,
61,
29195,
17563,
4722,
14432,
203,
565,
2254,
5034,
1071,
15105,
273,
6549,
31,
203,
565,
1758,
279,
6909,
1764,
8924,
31,
203,
377,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
2935,
31,
203,
27699,
203,
203,
565,
3885,
12,
2867,
277,
2894,
8924,
16,
1758,
389,
1826,
7285,
8924,
13,
1071,
288,
203,
3639,
279,
6909,
1764,
8924,
273,
389,
1826,
7285,
8924,
31,
203,
3639,
3410,
273,
374,
92,
8898,
74,
28,
70,
40,
27,
69,
28,
39,
2539,
3600,
23508,
713,
9172,
37,
23,
38,
5948,
23,
2539,
9349,
5895,
7950,
38,
26,
9897,
29,
31,
203,
540,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
277,
2894,
8924,
16,
4711,
2787,
380,
1728,
2826,
261,
2643,
10019,
203,
540,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1758,
12,
8443,
3631,
4711,
2787,
225,
380,
1728,
2826,
261,
2643,
10019,
203,
540,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1758,
12,
1826,
7285,
8924,
3631,
4711,
2787,
380,
1728,
2826,
261,
2643,
10019,
203,
565,
289,
203,
203,
27699,
27699,
565,
445,
2078,
3088,
1283,
1435,
3903,
3849,
1476,
1135,
261,
11890,
5034,
15329,
203,
4202,
327,
389,
2
] |
./partial_match/1/0xBB13E608888E5D30C09b13F89d27631056161B9F/sources/GNR.sol | Shortcuts for before cliff and after vesting cases. Interpolate all vested tokens. As before cliff the shortcut returns 0, we can use just this function to calculate it. vestedTokens = tokens * (time - start) / (vesting - start) | function calculateVestedTokens(
uint256 tokens,
uint256 time,
uint256 start,
uint256 cliff,
uint256 vesting) internal constant returns (uint256)
{
if (time < cliff) return 0;
if (time >= vesting) return tokens;
uint256 vestedTokens = safeDiv(
safeMul(
tokens,
safeSub(time, start)
),
safeSub(vesting, start)
);
return vestedTokens;
}
| 4,122,078 | [
1,
15576,
87,
364,
1865,
927,
3048,
471,
1839,
331,
10100,
6088,
18,
24301,
340,
777,
331,
3149,
2430,
18,
2970,
1865,
927,
3048,
326,
10995,
1135,
374,
16,
732,
848,
999,
2537,
333,
445,
358,
4604,
518,
18,
331,
3149,
5157,
273,
2430,
225,
261,
957,
300,
787,
13,
342,
261,
90,
10100,
300,
787,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
225,
445,
4604,
58,
3149,
5157,
12,
203,
565,
2254,
5034,
2430,
16,
203,
565,
2254,
5034,
813,
16,
203,
565,
2254,
5034,
787,
16,
203,
565,
2254,
5034,
927,
3048,
16,
203,
565,
2254,
5034,
331,
10100,
13,
2713,
5381,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
203,
565,
309,
261,
957,
411,
927,
3048,
13,
327,
374,
31,
203,
565,
309,
261,
957,
1545,
331,
10100,
13,
327,
2430,
31,
203,
203,
203,
565,
2254,
5034,
331,
3149,
5157,
273,
4183,
7244,
12,
203,
21394,
4183,
27860,
12,
203,
4766,
565,
2430,
16,
203,
4766,
565,
4183,
1676,
12,
957,
16,
787,
13,
203,
4766,
565,
262,
16,
203,
21394,
4183,
1676,
12,
90,
10100,
16,
787,
13,
203,
21394,
11272,
203,
203,
565,
327,
331,
3149,
5157,
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
] |
./full_match/5/0x0140aC40ac7806b965ccC1aEBEB34A63120d4113/sources/contracts/HelloWorld.sol | Accepts a string argument `initMessage`. | constructor(string memory initMessage) {
message = initMessage;
}
| 1,907,343 | [
1,
26391,
279,
533,
1237,
1375,
2738,
1079,
8338,
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,
282,
3885,
12,
1080,
3778,
1208,
1079,
13,
288,
203,
203,
203,
1377,
883,
273,
1208,
1079,
31,
203,
282,
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
] |
pragma solidity ^0.5.2;
import { IERC20 } from "openzeppelin-solidity/contracts/token/ERC20/IERC20.sol";
import { ERC721Full } from "openzeppelin-solidity/contracts/token/ERC721/ERC721Full.sol";
import { Math } from "openzeppelin-solidity/contracts/math/Math.sol";
import { SafeMath } from "openzeppelin-solidity/contracts/math/SafeMath.sol";
import { BytesLib } from "../common/lib/BytesLib.sol";
import { ECVerify } from "../common/lib/ECVerify.sol";
import { Merkle } from "../common/lib/Merkle.sol";
import { Lockable } from "../common/mixin/Lockable.sol";
import { RootChainable } from "../common/mixin/RootChainable.sol";
import { Registry } from "../common/Registry.sol";
import { IStakeManager } from "./IStakeManager.sol";
import { Validator } from "./Validator.sol";
import { ValidatorContract } from "./Validator.sol";
contract StakeManager is Validator, IStakeManager, RootChainable, Lockable {
using SafeMath for uint256;
using ECVerify for bytes32;
using Merkle for bytes32;
IERC20 public token;
address public registry;
// genesis/governance variables
uint256 public dynasty = 2**13; // unit: epoch 50 days
uint256 public checkpointReward = 10000 * (10**18); // @todo update according to Chain
uint256 public MIN_DEPOSIT_SIZE = (10**18); // in ERC20 token
uint256 public EPOCH_LENGTH = 256; // unit : block
uint256 public UNSTAKE_DELAY = dynasty.mul(2); // unit: epoch
uint256 public checkPointBlockInterval = 255;
// TODO: add events and gov. based update function
uint256 public proposerToSignerRewards = 10; // will be used with fraud proof
uint256 public validatorThreshold = 10; //128
uint256 public minLockInPeriod = 2; // unit: dynasty
uint256 public totalStaked;
uint256 public currentEpoch = 1;
uint256 public NFTCounter = 1;
uint256 public totalRewards;
uint256 public totalRewardsLiquidated;
uint256 public auctionPeriod = dynasty.div(4); // 1 week in epochs
bytes32 public accountStateRoot;
// on dynasty update certain amount of cooldown period where there is no validator auction
uint256 replacementCoolDown;
enum Status { Inactive, Active, Locked }
struct Validator {
uint256 amount;
uint256 reward;
uint256 claimedRewards;
uint256 activationEpoch;
uint256 deactivationEpoch;
uint256 jailTime;
address signer;
address contractAddress;
Status status;
}
struct Auction {
uint256 amount;
uint256 startEpoch;
address user;
}
struct State {
int256 amount;
int256 stakerCount;
}
// signer to Validator mapping
mapping (address => uint256) public signerToValidator;
// validator metadata
mapping (uint256 => Validator) public validators;
//Mapping for epoch to totalStake for that epoch
mapping (uint256 => State) public validatorState;
//Ongoing auctions for validatorId
mapping (uint256 => Auction) public validatorAuction;
constructor (address _registry, address _rootchain) ERC721Full("Matic Validator", "MV") public {
registry = _registry;
rootChain = _rootchain;
}
modifier onlyStaker(uint256 validatorId) {
require(ownerOf(validatorId) == msg.sender);
_;
}
modifier onlySlashingMananger() {
require(Registry(registry).getSlashingManagerAddress() == msg.sender);
_;
}
function stake(uint256 amount, address signer, bool isContract) external {
stakeFor(msg.sender, amount, signer, isContract);
}
function stakeFor(address user, uint256 amount, address signer, bool isContract) public onlyWhenUnlocked {
require(currentValidatorSetSize() < validatorThreshold);
require(balanceOf(user) == 0, "Only one time staking is allowed");
require(amount > MIN_DEPOSIT_SIZE);
require(signerToValidator[signer] == 0);
require(token.transferFrom(msg.sender, address(this), amount), "Transfer stake failed");
_stakeFor(user, amount, signer, isContract);
}
function _stakeFor(address user, uint256 amount, address signer, bool isContract) internal {
totalStaked = totalStaked.add(amount);
validators[NFTCounter] = Validator({
reward: 0,
amount: amount,
claimedRewards: 0,
activationEpoch: currentEpoch,
deactivationEpoch: 0,
jailTime: 0,
signer: signer,
contractAddress: isContract ? address(new ValidatorContract(user, registry)) : address(0x0),
status : Status.Active
});
_mint(user, NFTCounter);
signerToValidator[signer] = NFTCounter;
updateTimeLine(currentEpoch, int256(amount), 1);
// no Auctions for 1 dynasty
validatorAuction[NFTCounter].startEpoch = currentEpoch.add(dynasty);
emit Staked(signer, NFTCounter, currentEpoch, amount, totalStaked);
NFTCounter = NFTCounter.add(1);
}
function perceivedStakeFactor(uint256 validatorId) internal returns(uint256){
// TODO: use age, rewardRatio, and slashing/reward rate
return 1;
}
function startAuction(uint256 validatorId, uint256 amount) external {
require(isValidator(validatorId));
// when dynasty period is updated validators are in cool down period
require(replacementCoolDown == 0 || replacementCoolDown <= currentEpoch, "Cool down period");
require(auctionPeriod >= currentEpoch.sub(validatorAuction[validatorId].startEpoch), "Invalid auction period");
// (dynasty--auctionPeriod)--(dynasty--auctionPeriod)--(dynasty--auctionPeriod)
// if it's auctionPeriod then will get residue from (CurrentPeriod of validator )%(dynasty--auctionPeriod)
// make sure that its `auctionPeriod` window
// dynasty = 30, auctionPeriod = 7, activationEpoch = 1, currentEpoch = 39
// residue 1 = (39-1)% (30+7), if residue-dynasty > 0 it's `auctionPeriod`
require((currentEpoch.sub(validators[validatorId].activationEpoch) % dynasty.add(auctionPeriod)) > dynasty, "Not an auction time");
require(token.transferFrom(msg.sender, address(this), amount), "Transfer amount failed");
uint256 perceivedStake = validators[validatorId].amount.mul(perceivedStakeFactor(validatorId));
perceivedStake = Math.max(perceivedStake, validatorAuction[validatorId].amount);
require(perceivedStake < amount, "Must bid higher amount");
// create new auction
if (validatorAuction[validatorId].amount == 0) {
validatorAuction[validatorId] = Auction({
amount: amount,
startEpoch: currentEpoch,
user: msg.sender
});
} else { //replace prev auction
Auction storage auction = validatorAuction[validatorId];
require(token.transfer(auction.user, auction.amount));
auction.amount = amount;
auction.user = msg.sender;
}
emit StartAuction(validatorId, validators[validatorId].amount, validatorAuction[validatorId].amount);
}
function confirmAuctionBid(uint256 validatorId, address signer, bool isContract) external onlyWhenUnlocked {
Auction storage auction = validatorAuction[validatorId];
Validator storage validator = validators[validatorId];
require(auction.user == msg.sender);
require(auctionPeriod.add(auction.startEpoch) <= currentEpoch, "Confirmation is not allowed before auctionPeriod");
// validator is last auctioner
if (auction.user == ownerOf(validatorId)) {
uint256 refund = validator.amount;
require(token.transfer(auction.user, refund));
validator.amount = auction.amount;
//cleanup auction data
auction.amount = 0;
auction.user = address(0x0);
auction.startEpoch = currentEpoch.add(dynasty);
//update total stake amount
totalStaked = totalStaked.add(validator.amount.sub(refund));
emit StakeUpdate(validatorId, refund, validator.amount);
emit ConfirmAuction(validatorId, validatorId, validator.amount);
} else {
// dethrone
_unstake(validatorId, currentEpoch);
_stakeFor(auction.user, auction.amount, signer, isContract);
emit ConfirmAuction(NFTCounter.sub(1), validatorId, auction.amount);
delete validatorAuction[validatorId];
}
}
function unstake(uint256 validatorId) external onlyStaker(validatorId) {
require(validatorAuction[validatorId].amount == 0, "Wait for auction completion");
uint256 exitEpoch = currentEpoch.add(1);// notice period
require(validators[validatorId].activationEpoch > 0 &&
validators[validatorId].deactivationEpoch == 0 &&
validators[validatorId].status == Status.Active);
_unstake(validatorId, exitEpoch);
}
function _unstake(uint256 validatorId, uint256 exitEpoch) internal {
//Todo: add state here consider jail
uint256 amount = validators[validatorId].amount;
validators[validatorId].deactivationEpoch = exitEpoch;
// unbond all delegators in future
int256 delegationAmount = 0;
if (validators[validatorId].contractAddress != address(0x0)) {
delegationAmount = ValidatorContract(validators[validatorId].contractAddress).unBondAllLazy(exitEpoch);
}
// update future
updateTimeLine(exitEpoch, -(int256(amount) + delegationAmount ), -1);
emit UnstakeInit(msg.sender, validatorId, exitEpoch, amount);
}
function unstakeClaim(uint256 validatorId) public onlyStaker(validatorId) {
// can only claim stake back after WITHDRAWAL_DELAY
require(validators[validatorId].deactivationEpoch > 0 && validators[validatorId].deactivationEpoch.add(WITHDRAWAL_DELAY) <= currentEpoch);
uint256 amount = validators[validatorId].amount;
totalStaked = totalStaked.sub(amount);
// TODO :add slashing here use soft slashing in slash amt variable
_burn(validatorId);
delete signerToValidator[validators[validatorId].signer];
// delete validators[validatorId];
require(token.transfer(msg.sender, amount + validators[validatorId].reward));
emit Unstaked(msg.sender, validatorId, amount, totalStaked);
}
// slashing and jail interface
function restake(uint256 validatorId, uint256 amount, bool stakeRewards) public onlyStaker(validatorId) {
require(validators[validatorId].deactivationEpoch < currentEpoch, "No use of restaking");
if (amount > 0) {
require(token.transferFrom(msg.sender, address(this), amount), "Transfer stake");
}
if (stakeRewards) {
amount += validators[validatorId].reward;
validators[validatorId].reward = 0;
}
totalStaked = totalStaked.add(amount);
validators[validatorId].amount += amount;
validatorState[currentEpoch].amount = (
validatorState[currentEpoch].amount + int256(amount));
emit StakeUpdate(validatorId, validators[validatorId].amount.sub(amount), validators[validatorId].amount);
emit ReStaked(validatorId, validators[validatorId].amount, totalStaked);
}
function claimRewards(uint256 validatorId, uint256 accountBalance, uint256 index, bytes memory proof) public /*onlyStaker(validatorId) */ {
// accountState = keccak256(abi.encodePacked(validatorId, accountBalance))
require(keccak256(abi.encodePacked(validatorId, accountBalance)).checkMembership(index, accountStateRoot, proof));
uint256 _reward = accountBalance.sub(validators[validatorId].claimedRewards);
address _contract = validators[validatorId].contractAddress;
if (_contract == address(0x0)) {
validators[validatorId].reward = validators[validatorId].reward.add(_reward);
}
else {
// TODO: delegator bond/share rate if return needs to be updated periodically
// otherwise validator can delay and get all the delegators reward
ValidatorContract(_contract).updateRewards(_reward, currentEpoch, validators[validatorId].amount);
}
totalRewardsLiquidated += _reward;
require(totalRewardsLiquidated <= totalRewards, "Liquidating more rewards then checkpoints submitted");// pos 2/3+1 is colluded
validators[validatorId].claimedRewards = accountBalance;
emit ClaimRewards(validatorId, _reward, accountBalance);
}
function withdrawRewards(uint256 validatorId) public onlyStaker(validatorId) {
uint256 amount = validators[validatorId].reward;
address _contract = validators[validatorId].contractAddress;
if (_contract != address(0x0)) {
amount = amount.add(ValidatorContract(_contract).withdrawRewardsValidator());
}
validators[validatorId].reward = 0;
require(token.transfer(msg.sender, amount), "Insufficent rewards");
}
function delegationTransfer(uint256 amount, address delegator) external {
require(Registry(registry).getDelegationManagerAddress() == msg.sender);
require(token.transfer(delegator, amount), "Insufficent rewards");
}
// if not jailed then in state of warning, else will be unstaking after x epoch
function slash(uint256 validatorId, uint256 slashingRate, uint256 jailCheckpoints) public onlySlashingMananger {
// if contract call contract.slash
if (validators[validatorId].contractAddress != address(0x0)) {
ValidatorContract(validators[validatorId].contractAddress).slash(slashingRate, currentEpoch, currentEpoch);
}
uint256 amount = validators[validatorId].amount.mul(slashingRate).div(100);
validators[validatorId].amount = validators[validatorId].amount.sub(amount);
if(validators[validatorId].amount < MIN_DEPOSIT_SIZE || jailCheckpoints > 0) {
jail(validatorId, jailCheckpoints);
}
// todo: slash event
emit StakeUpdate(validatorId, validators[validatorId].amount.add(amount), validators[validatorId].amount);
}
function unJail(uint256 validatorId) public onlyStaker(validatorId) {
require(validators[validatorId].deactivationEpoch > currentEpoch &&
validators[validatorId].jailTime <= currentEpoch &&
validators[validatorId].status == Status.Locked);
uint256 amount = validators[validatorId].amount;
require(amount >= MIN_DEPOSIT_SIZE);
uint256 exitEpoch = validators[validatorId].deactivationEpoch;
int256 delegationAmount = 0;
if (validators[validatorId].contractAddress != address(0x0)) {
delegationAmount = ValidatorContract(validators[validatorId].contractAddress).revertLazyUnBonding(exitEpoch);
}
// undo timline so that validator is normal validator
updateTimeLine(exitEpoch, (int256(amount) + delegationAmount ), 1);
validators[validatorId].deactivationEpoch = 0;
validators[validatorId].status = Status.Active;
validators[validatorId].jailTime = 0;
}
// in context of slashing
function jail(uint256 validatorId, uint256 jailCheckpoints) public /** only*/ {
// Todo: requires and more conditions
uint256 amount = validators[validatorId].amount;
// should unbond instantly
uint256 exitEpoch = currentEpoch.add(UNSTAKE_DELAY); // jail period
int256 delegationAmount = 0;
validators[validatorId].jailTime = jailCheckpoints;
if (validators[validatorId].contractAddress != address(0x0)) {
delegationAmount = ValidatorContract(validators[validatorId].contractAddress).unBondAllLazy(exitEpoch);
}
// update future in case of no `unJail`
updateTimeLine(exitEpoch, -(int256(amount) + delegationAmount ), -1);
validators[validatorId].deactivationEpoch = exitEpoch;
validators[validatorId].status = Status.Locked;
emit Jailed(validatorId, exitEpoch);
}
function updateTimeLine(uint256 epoch, int256 amount, int256 stakerCount) private {
validatorState[epoch].amount += amount;
validatorState[epoch].stakerCount += stakerCount;
}
// returns valid validator for current epoch
function getCurrentValidatorSet() public view returns (uint256[] memory) {
uint256[] memory _validators = new uint256[](validatorThreshold);
uint256 validator;
uint256 k = 0;
for (uint96 i = 0;i < totalSupply() ;i++) {
validator = tokenByIndex(i);
if (isValidator(validator)) {
_validators[k++] = validator;
}
}
return _validators;
}
function getStakerDetails(uint256 validatorId) public view returns(uint256, uint256, uint256, address, uint256) {
return (
validators[validatorId].amount,
validators[validatorId].activationEpoch,
validators[validatorId].deactivationEpoch,
validators[validatorId].signer,
uint256(validators[validatorId].status)
);
}
function getValidatorId(address user) public view returns(uint256) {
return tokenOfOwnerByIndex(user, 0);
}
function totalStakedFor(address user) external view returns (uint256) {
if (user == address(0x0) || balanceOf(user) == 0) {
return 0;
}
return validators[tokenOfOwnerByIndex(user, 0)].amount;
}
function supportsHistory() external pure returns (bool) {
return false;
}
// set staking Token
function setToken(address _token) public onlyOwner {
require(_token != address(0x0));
token = IERC20(_token);
}
// Change the number of validators required to allow a passed header root
function updateValidatorThreshold(uint256 newThreshold) public onlyOwner {
require(newThreshold > 0);
emit ThresholdChange(newThreshold, validatorThreshold);
validatorThreshold = newThreshold;
}
function updateCheckPointBlockInterval(uint256 _blocks) public onlyOwner {
require(_blocks > 0, "Blocks interval must be non-zero");
checkPointBlockInterval = _blocks;
}
// Change reward for each checkpoint
function updateCheckpointReward(uint256 newReward) public onlyOwner {
require(newReward > 0);
emit RewardUpdate(newReward, checkpointReward);
checkpointReward = newReward;
}
function updateValidatorState(uint256 validatorId, uint256 epoch, int256 amount) public {
require(Registry(registry).getDelegationManagerAddress() == msg.sender);
require(epoch >= currentEpoch, "Can't change past");
validatorState[epoch].amount = (
validatorState[epoch].amount + amount
);
}
function updateDynastyValue(uint256 newDynasty) public onlyOwner {
require(newDynasty > 0);
emit DynastyValueChange(newDynasty, dynasty);
dynasty = newDynasty;
UNSTAKE_DELAY = dynasty.div(2);
WITHDRAWAL_DELAY = dynasty.mul(2);
auctionPeriod = dynasty.div(4);
// set cool down period
replacementCoolDown = currentEpoch.add(auctionPeriod);
}
function updateSigner(uint256 validatorId, address _signer) public onlyStaker(validatorId) {
require(_signer != address(0x0) && signerToValidator[_signer] == 0);
// update signer event
emit SignerChange(validatorId, validators[validatorId].signer, _signer);
delete signerToValidator[validators[validatorId].signer];
signerToValidator[_signer] = validatorId;
validators[validatorId].signer = _signer;
}
function finalizeCommit() internal {
uint256 nextEpoch = currentEpoch.add(1);
// update totalstake and validator count
validatorState[nextEpoch].amount = (
validatorState[currentEpoch].amount + validatorState[nextEpoch].amount
);
validatorState[nextEpoch].stakerCount = (
validatorState[currentEpoch].stakerCount + validatorState[nextEpoch].stakerCount
);
// erase old data/history
delete validatorState[currentEpoch];
currentEpoch = nextEpoch;
}
function updateMinLockInPeriod(uint256 epochs) public onlyOwner {
minLockInPeriod = epochs;
}
function currentValidatorSetSize() public view returns (uint256) {
return uint256(validatorState[currentEpoch].stakerCount);
}
function currentValidatorSetTotalStake() public view returns (uint256) {
return uint256(validatorState[currentEpoch].amount);
}
function getValidatorContract(uint256 validatorId) public view returns(address) {
return validators[validatorId].contractAddress;
}
function isValidator(uint256 validatorId) public view returns (bool) {
return (
validators[validatorId].amount > 0 &&
(validators[validatorId].activationEpoch != 0 &&
validators[validatorId].activationEpoch <= currentEpoch ) &&
(validators[validatorId].deactivationEpoch == 0 ||
validators[validatorId].deactivationEpoch > currentEpoch) &&
validators[validatorId].status == Status.Active // Todo: reduce logic
);
}
function checkSignatures(uint256 blockInterval, bytes32 voteHash, bytes32 stateRoot, bytes memory sigs) public onlyRootChain returns(uint256) {
uint256 stakePower;
uint256 _totalStake;
(stakePower, _totalStake) = checkTwoByThreeMajority(voteHash, sigs);
// checkpoint rewards are based on BlockInterval multiplied on `checkpointReward`
// with actual `blockInterval`
// eg. checkpointReward = 10 Tokens, checkPointBlockInterval = 250, blockInterval = 500 then reward
// for this checkpoint is 20 Tokens
uint256 _reward = blockInterval.mul(checkpointReward).div(checkPointBlockInterval);
_reward = Math.min(checkpointReward, _reward).mul(stakePower).div(_totalStake);
totalRewards = totalRewards.add(_reward);
// update stateMerkleTree root for accounts balance on heimdall chain
// for previous checkpoint rewards
accountStateRoot = stateRoot;
finalizeCommit();
return _reward;
}
function checkTwoByThreeMajority(bytes32 voteHash, bytes memory sigs) public view returns(uint256, uint256) {
// total voting power
uint256 stakePower;
uint256 validatorId;
address lastAdd = address(0x0); // cannot have address(0x0) as an owner
for (uint64 i = 0; i < sigs.length; i += 65) {
bytes memory sigElement = BytesLib.slice(sigs, i, 65);
address signer = voteHash.ecrecovery(sigElement);
validatorId = signerToValidator[signer];
// check if signer is stacker and not proposer
if (signer == lastAdd) {
break;
}
else if (
isValidator(validatorId) &&
signer > lastAdd
) {
lastAdd = signer;
address _contract = validators[validatorId].contractAddress;
stakePower = stakePower.add(validators[validatorId].amount);
// add delegation power
if (_contract != address(0x0)) {
stakePower = stakePower.add(ValidatorContract(_contract).delegatedAmount());
}
}
}
uint256 _totalStake = currentValidatorSetTotalStake();
require(stakePower >= _totalStake.mul(2).div(3).add(1));
return (stakePower, _totalStake);
}
function challangeStateRootUpdate(bytes memory checkpointTx /* txData from submitCheckpoint */) public {
// TODO: check for 2/3+1 sig and validate non-inclusion in newStateUpdate
}
}
| @todo update according to Chain
| uint256 public checkpointReward = 10000 * (10**18); | 2,484,350 | [
1,
36,
9012,
1089,
4888,
358,
7824,
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,
225,
2254,
5034,
1071,
9776,
17631,
1060,
273,
12619,
380,
261,
2163,
636,
2643,
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
] |
pragma solidity 0.5.11;
// WARNING - `executeActionWithAtomicBatchCalls` has a `bytes[]` argument that
// requires ABIEncoderV2, and the alternatives are pretty convoluted. Consider
// losing that function and ABIEncoderV2 for the V1 smart wallet implementation.
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../../interfaces/DharmaSmartWalletImplementationV0Interface.sol";
import "../../../interfaces/DharmaSmartWalletImplementationV1Interface.sol";
import "../../../interfaces/DharmaSmartWalletImplementationV4Interface.sol";
import "../../../interfaces/CTokenInterface.sol";
import "../../../interfaces/CEtherInterface.sol";
import "../../../interfaces/USDCV1Interface.sol";
import "../../../interfaces/ComptrollerInterface.sol";
import "../../../interfaces/DharmaKeyRegistryInterface.sol";
import "../../../interfaces/ERC1271.sol";
/**
* @title DharmaSmartWalletImplementationV4
* @notice The V4 implementation for the Dharma smart wallet is a non-custodial,
* meta-transaction-enabled wallet with helper functions to facilitate lending
* funds using CompoundV2, and with a security backstop provided by Dharma Labs
* prior to making withdrawals or borrows. It also contains methods to support
* account recovery and generic actions, including in an atomic batch. The smart
* wallet instances utilizing this implementation are deployed through the
* Dharma Smart Wallet Factory via `CREATE2`, which allows for their address to
* be known ahead of time, and any Dai, USDC, or Ether that has already been
* sent into that address will automatically be deposited into Compound upon
* deployment of the new smart wallet instance.
*
* NOTE: this implementation is still under development and has known bugs and
* areas for improvement. The actual V4 implementation will likely be quite
* different than what is currently contained here.
*/
contract DharmaSmartWalletImplementationVX is
DharmaSmartWalletImplementationV0Interface,
DharmaSmartWalletImplementationV1Interface,
DharmaSmartWalletImplementationV4Interface {
using Address for address;
using ECDSA for bytes32;
// WARNING: DO NOT REMOVE OR REORDER STORAGE WHEN WRITING NEW IMPLEMENTATIONS!
// The user signing key associated with this account is in storage slot 0.
// It is the core differentiator when it comes to the account in question.
address private _userSigningKey;
// The nonce associated with this account is in storage slot 1. Every time a
// signature is submitted, it must have the appropriate nonce, and once it has
// been accepted the nonce will be incremented.
uint256 private _nonce;
// The self-call context flag is in storage slot 2. Some protected functions
// may only be called externally from calls originating from other methods on
// this contract, which enables appropriate exception handling on reverts.
// Any storage should only be set immediately preceding a self-call and should
// be cleared upon entering the protected function being called.
bytes4 internal _selfCallContext;
// END STORAGE DECLARATIONS - DO NOT REMOVE OR REORDER STORAGE ABOVE HERE!
// The smart wallet version will be used when constructing valid signatures.
uint256 internal constant _DHARMA_SMART_WALLET_VERSION = 4;
// The Dharma Key Registry holds a public key for verifying meta-transactions.
DharmaKeyRegistryInterface internal constant _DHARMA_KEY_REGISTRY = (
DharmaKeyRegistryInterface(0x000000000D38df53b45C5733c7b34000dE0BDF52)
);
// Account recovery is facilitated using a hard-coded recovery manager,
// controlled by Dharma and implementing appropriate timelocks.
address internal constant _ACCOUNT_RECOVERY_MANAGER = address(
0x00000000004cDa75701EeA02D1F2F9BDcE54C10D
);
// This contract interfaces with Dai, USDC, and related CompoundV2 contracts.
CTokenInterface internal constant _CDAI = CTokenInterface(
0xF5DCe57282A584D2746FaF1593d3121Fcac444dC // mainnet
);
CTokenInterface internal constant _CUSDC = CTokenInterface(
0x39AA39c021dfbaE8faC545936693aC917d5E7563 // mainnet
);
CEtherInterface internal constant _CETH = CEtherInterface(
0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5 // mainnet
);
IERC20 internal constant _DAI = IERC20(
0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359 // mainnet
);
IERC20 internal constant _USDC = IERC20(
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
USDCV1Interface internal constant _USDC_NAUGHTY = USDCV1Interface(
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
ComptrollerInterface internal constant _COMPTROLLER = ComptrollerInterface(
0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B // mainnet
);
// Compound returns a value of 0 to indicate success, or lack of an error.
uint256 internal constant _COMPOUND_SUCCESS = 0;
// ERC-1271 must return this magic value when `isValidSignature` is called.
bytes4 internal constant _ERC_1271_MAGIC_VALUE = bytes4(0x20c13b0b);
// Automatically deposit ETH if enough gas is supplied to fallback function.
// TODO: determine the appropriate value to use!
uint256 internal constant _AUTOMATIC_ETH_DEPOSIT_GAS = 100000;
function () external payable {
if (
msg.sender != address(_CETH) && // do not redeposit on withdrawals.
gasleft() > _AUTOMATIC_ETH_DEPOSIT_GAS // only deposit with adequate gas.
) {
_depositEtherOnCompound();
}
}
/**
* @notice In initializer, set up user signing key, set approval on the cDAI
* and cUSDC contracts, deposit any Dai, USDC, and ETH already at the address
* to Compound, and enter markets for cDAI, cUSDC, and cETH. Note that this
* initializer is only callable while the smart wallet instance is still in
* the contract creation phase.
* @param userSigningKey address The initial user signing key for the smart
* wallet.
*/
function initialize(address userSigningKey) external {
// Ensure that this function is only callable during contract construction.
assembly { if extcodesize(address) { revert(0, 0) } }
// Set up the user's signing key and emit a corresponding event.
_setUserSigningKey(userSigningKey);
// Approve the cDAI contract to transfer Dai on behalf of this contract.
if (_setFullApproval(AssetType.DAI)) {
// Get the current Dai balance on this contract.
uint256 daiBalance = _DAI.balanceOf(address(this));
// Try to deposit any dai balance on Compound.
_depositOnCompound(AssetType.DAI, daiBalance);
}
// Approve the cUSDC contract to transfer USDC on behalf of this contract.
if (_setFullApproval(AssetType.USDC)) {
// Get the current USDC balance on this contract.
uint256 usdcBalance = _USDC.balanceOf(address(this));
// Try to deposit any USDC balance on Compound.
_depositOnCompound(AssetType.USDC, usdcBalance);
}
// Try to deposit any Ether balance on Compound.
_depositOnCompound(AssetType.ETH, address(this).balance);
// Enter DAI + USDC + ETH markets to enable using them as borrow collateral.
_enterMarkets();
}
/**
* @notice Use all Dai, USDC, and ETH currently residing at this address to
* first repay any outstanding borrows, then to deposit and mint corresponding
* cTokens on Compound. If some step of this function fails, the function
* itself will still succeed, but an ExternalError with information on what
* went wrong will be emitted.
*/
function repayAndDeposit() external {
// Get the current Dai balance on this contract.
uint256 daiBalance = _DAI.balanceOf(address(this));
if (daiBalance > 0) {
// First use funds to try to repay Dai borrow balance.
uint256 remainingDai = _repayOnCompound(AssetType.DAI, daiBalance);
// Then deposit any remaining Dai.
_depositOnCompound(AssetType.DAI, remainingDai);
}
// Get the current USDC balance on this contract.
uint256 usdcBalance = _USDC.balanceOf(address(this));
// If there is any USDC balance, check for adequate approval for cUSDC.
if (usdcBalance > 0) {
uint256 usdcAllowance = _USDC.allowance(address(this), address(_CUSDC));
// If allowance is insufficient, try to set it before depositing.
if (usdcAllowance < usdcBalance) {
if (_setFullApproval(AssetType.USDC)) {
// First use funds to try to repay Dai borrow balance.
uint256 remainingUsdc = _repayOnCompound(AssetType.USDC, usdcBalance);
// Then deposit any remaining USDC.
_depositOnCompound(AssetType.USDC, remainingUsdc);
}
// Otherwise, go ahead and try the deposit.
} else {
// First use funds to try to repay Dai borrow balance.
uint256 remainingUsdc = _repayOnCompound(AssetType.USDC, usdcBalance);
// Then deposit any remaining USDC.
_depositOnCompound(AssetType.USDC, remainingUsdc);
}
}
// Deposit any Ether balance on this contract.
_depositEtherOnCompound();
}
/**
* @notice Withdraw Dai to a provided recipient address by redeeming the
* underlying Dai from the cDAI contract and transferring it to the recipient.
* All Dai in Compound and in the smart wallet itself can be withdrawn by
* providing an amount of uint256(-1) or 0xfff...fff. This function can be
* called directly by the account set as the global key on the Dharma Key
* Registry, or by any relayer that provides a signed message from the same
* keyholder. The nonce used for the signature must match the current nonce on
* the smart wallet, and gas supplied to the call must exceed the specified
* minimum action gas, plus the gas that will be spent before the gas check is
* reached - usually somewhere around 25,000 gas. If the withdrawal fails, an
* ExternalError with additional details on what went wrong will be emitted.
* Note that some dust may still be left over, even in the event of a max
* withdrawal, due to the fact that Dai has a higher precision than cDAI. Also
* note that the withdrawal will fail in the event that Compound does not have
* sufficient Dai available to withdraw.
* @param amount uint256 The amount of Dai to withdraw.
* @param recipient address The account to transfer the withdrawn Dai to.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return True if the withdrawal succeeded, otherwise false.
*/
function withdrawDai(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.DAIWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set the self-call context so we can call _withdrawDaiAtomic.
_selfCallContext = this.withdrawDai.selector;
// Make the atomic self-call - if redeemUnderlying fails on cDAI, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (the Dai transfer) fails, it will revert
// and roll back the first part of the call, and we'll fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._withdrawDaiAtomic.selector, amount, recipient
));
// If the atomic call failed, diagnose the reason and emit an event.
if (!ok) {
// This revert could be caused by cDai MathError or Dai transfer error.
_diagnoseAndEmitErrorRelatedToWithdrawal(AssetType.DAI);
} else {
// Set ok to false if the call succeeded but the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
/**
* @notice Protected function that can only be called from `withdrawDai` on
* this contract. It will attempt to withdraw the supplied amount of Dai, or
* the maximum amount if specified using `uint256(-1)`, to the supplied
* recipient address by redeeming the underlying Dai from the cDAI contract
* and transferring it to the recipient. An ExternalError will be emitted and
* the transfer will be skipped if the call to `redeemUnderlying` fails, and
* any revert will be caught by `withdrawDai` and diagnosed in order to emit
* an appropriate ExternalError as well.
* @param amount uint256 The amount of Dai to withdraw.
* @param recipient address The account to transfer the withdrawn Dai to.
* @return True if the withdrawal succeeded, otherwise false.
*/
function _withdrawDaiAtomic(
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.withdrawDai.selector);
// If amount = 0xfff...fff, withdraw the maximum amount possible.
bool maxWithdraw = (amount == uint256(-1));
uint256 redeemUnderlyingAmount;
if (maxWithdraw) {
redeemUnderlyingAmount = _CDAI.balanceOfUnderlying(address(this));
} else {
redeemUnderlyingAmount = amount;
}
// Attempt to withdraw specified Dai amount from Compound before proceeding.
if (_withdrawFromCompound(AssetType.DAI, redeemUnderlyingAmount)) {
// At this point dai transfer *should* never fail - wrap it just in case.
if (maxWithdraw) {
require(_DAI.transfer(recipient, _DAI.balanceOf(address(this))));
} else {
require(_DAI.transfer(recipient, amount));
}
success = true;
}
}
function borrowDai(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.DAIBorrow,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set the self-call context so we can call _borrowDaiAtomic.
_selfCallContext = this.borrowDai.selector;
// Make the atomic self-call - if borrow fails on cDAI, it will succeed but
// nothing will happen except firing an ExternalError event. If the second
// part of the self-call (the Dai transfer) fails, it will revert and roll
// back the first part of the call, and we'll fire an ExternalError event
// after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._borrowDaiAtomic.selector, amount, recipient
));
if (!ok) {
emit ExternalError(address(_DAI), "DAI contract reverted on transfer.");
} else {
// Ensure that ok == false in the event the borrow failed.
ok = abi.decode(returnData, (bool));
}
}
function _borrowDaiAtomic(
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.borrowDai.selector);
if (_borrowFromCompound(AssetType.DAI, amount)) {
// at this point dai transfer *should* never fail - wrap it just in case.
require(_DAI.transfer(recipient, amount));
success = true;
}
}
/**
* @notice Withdraw USDC to a provided recipient address by redeeming the
* underlying USDC from the cUSDC contract and transferring it to recipient.
* All USDC in Compound and in the smart wallet itself can be withdrawn by
* providing an amount of uint256(-1) or 0xfff...fff. This function can be
* called directly by the account set as the global key on the Dharma Key
* Registry, or by any relayer that provides a signed message from the same
* keyholder. The nonce used for the signature must match the current nonce on
* the smart wallet, and gas supplied to the call must exceed the specified
* minimum action gas, plus the gas that will be spent before the gas check is
* reached - usually somewhere around 25,000 gas. If the withdrawal fails, an
* ExternalError with additional details on what went wrong will be emitted.
* Note that the USDC contract can be paused and also allows for blacklisting
* accounts - either of these possibilities may cause a withdrawal to fail. In
* addition, Compound may not have sufficient USDC available at the time to
* withdraw.
* @param amount uint256 The amount of USDC to withdraw.
* @param recipient address The account to transfer the withdrawn USDC to.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return True if the withdrawal succeeded, otherwise false.
*/
function withdrawUSDC(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.USDCWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set the self-call context so we can call _withdrawUSDCAtomic.
_selfCallContext = this.withdrawUSDC.selector;
// Make the atomic self-call - if redeemUnderlying fails on cUSDC, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (USDC transfer) fails, it will revert
// and roll back the first part of the call, and we'll fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._withdrawUSDCAtomic.selector, amount, recipient
));
if (!ok) {
// This revert could be caused by cUSDC MathError or USDC transfer error.
_diagnoseAndEmitErrorRelatedToWithdrawal(AssetType.USDC);
} else {
// Ensure that ok == false in the event the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
/**
* @notice Protected function that can only be called from `withdrawUSDC` on
* this contract. It will attempt to withdraw the supplied amount of USDC, or
* the maximum amount if specified using `uint256(-1)`, to the supplied
* recipient address by redeeming the underlying USDC from the cUSDC contract
* and transferring it to the recipient. An ExternalError will be emitted and
* the transfer will be skipped if the call to `redeemUnderlying` fails, and
* any revert will be caught by `withdrawUSDC` and diagnosed in order to emit
* an appropriate ExternalError as well.
* @param amount uint256 The amount of USDC to withdraw.
* @param recipient address The account to transfer the withdrawn USDC to.
* @return True if the withdrawal succeeded, otherwise false.
*/
function _withdrawUSDCAtomic(
uint256 amount,
address recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.withdrawUSDC.selector);
// If amount = 0xfff...fff, withdraw the maximum amount possible.
bool maxWithdraw = (amount == uint256(-1));
uint256 redeemUnderlyingAmount;
if (maxWithdraw) {
redeemUnderlyingAmount = _CUSDC.balanceOfUnderlying(address(this));
} else {
redeemUnderlyingAmount = amount;
}
// Try to withdraw specified USDC amount from Compound before proceeding.
if (_withdrawFromCompound(AssetType.USDC, redeemUnderlyingAmount)) {
// Ensure that the USDC transfer does not fail.
if (maxWithdraw) {
require(_USDC.transfer(recipient, _USDC.balanceOf(address(this))));
} else {
require(_USDC.transfer(recipient, amount));
}
success = true;
}
}
function borrowUSDC(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.USDCBorrow,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set the self-call context so we can call _borrowUSDCAtomic.
_selfCallContext = this.borrowUSDC.selector;
// Make the atomic self-call - if borrow fails on cUSDC, it will succeed but
// nothing will happen except firing an ExternalError event. If the second
// part of the self-call (USDC transfer) fails, it will revert and roll back
// the first part of the call, and we'll fire an ExternalError event after
// returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._borrowUSDCAtomic.selector, amount, recipient
));
if (!ok) {
// Find out why USDC transfer reverted (doesn't give revert reasons).
_diagnoseAndEmitUSDCSpecificError(_USDC.transfer.selector);
} else {
// Ensure that ok == false in the event the borrow failed.
ok = abi.decode(returnData, (bool));
}
}
function _borrowUSDCAtomic(uint256 amount, address recipient) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.borrowUSDC.selector);
if (_borrowFromCompound(AssetType.USDC, amount)) {
// ensure that the USDC transfer does not fail.
require(_USDC.transfer(recipient, amount));
success = true;
}
}
function withdrawEther(
uint256 amount,
address payable recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.ETHWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set the self-call context so we can call _withdrawEtherAtomic.
_selfCallContext = this.withdrawEther.selector;
// Make the atomic self-call - if redeemUnderlying fails on cDAI, it will
// succeed but nothing will happen except firing an ExternalError event. If
// the second part of the self-call (the Dai transfer) fails, it will revert
// and roll back the first part of the call, and we'll fire an ExternalError
// event after returning from the failed call.
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._withdrawEtherAtomic.selector, amount, recipient
));
if (!ok) {
emit ExternalError(address(this), "Ether transfer was unsuccessful.");
} else {
// Ensure that ok == false in the event the withdrawal failed.
ok = abi.decode(returnData, (bool));
}
}
function _withdrawEtherAtomic(
uint256 amount,
address payable recipient
) external returns (bool success) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.withdrawEther.selector);
if (_withdrawFromCompound(AssetType.ETH, amount)) {
recipient.transfer(amount);
success = true;
}
}
/**
* @notice Allow a signatory to increment the nonce at any point. The current
* nonce needs to be provided as an argument to the a signature so as not to
* enable griefing attacks. All arguments can be omitted if called directly.
* No value is returned from this function - it will either succeed or revert.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param signature bytes A signature that resolves to either the public key
* set for this account in storage slot zero, `_userSigningKey`, or the public
* key returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function cancel(
uint256 minimumActionGas,
bytes calldata signature
) external {
// Ensure the caller or the supplied signature is valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.Cancel,
abi.encode(),
minimumActionGas,
signature,
signature
);
}
function executeAction(
address to,
bytes calldata data,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok, bytes memory returnData) {
// Ensure that the `to` address is a contract and is not this contract.
_ensureValidGenericCallTarget(to);
// Ensure caller and/or supplied signatures are valid and increment nonce.
(bytes32 actionID, uint256 nonce) = _validateActionAndIncrementNonce(
ActionType.Generic,
abi.encode(to, data),
minimumActionGas,
userSignature,
dharmaSignature
);
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this action. However, the call
// itself may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Perform the action via low-level call and set return values using result.
(ok, returnData) = to.call(data);
// Emit a CallSuccess or CallFailure event based on the outcome of the call.
if (ok) {
// Note: while the call succeeded, the action may still have "failed"
// (for example, successful calls to Compound can still return an error).
emit CallSuccess(actionID, false, nonce, to, data, returnData);
} else {
// Note: while the call failed, the nonce will still be incremented, which
// will invalidate all supplied signatures.
emit CallFailure(actionID, nonce, to, data, string(returnData));
}
}
/**
* @notice Allow signatory to set a new user signing key. The current nonce
* needs to be provided as an argument to the a signature so as not to enable
* griefing attacks. No value is returned from this function - it will either
* succeed or revert.
* @param userSigningKey address The new user signing key to set on this smart
* wallet.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
*/
function setUserSigningKey(
address userSigningKey,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external {
// Ensure caller and/or supplied signatures are valid and increment nonce.
_validateActionAndIncrementNonce(
ActionType.SetUserSigningKey,
abi.encode(userSigningKey),
minimumActionGas,
userSignature,
dharmaSignature
);
// Set new user signing key on smart wallet and emit a corresponding event.
_setUserSigningKey(userSigningKey);
}
// Allow the account recovery manager to change the user signing key.
function recover(address newUserSigningKey) external {
require(
msg.sender == _ACCOUNT_RECOVERY_MANAGER,
"Only the account recovery manager may call this function."
);
// Set up the user's new dharma key and emit a corresponding event.
_setUserSigningKey(newUserSigningKey);
}
/**
* @notice Retrieve the Dai, USDC, and ETH balances held by the smart wallet,
* both directly and in Compound. This is not a view function since Compound
* will calculate accrued interest as part of the underlying balance checks,
* but can still be called from an off-chain source as though it were a view
* function.
* @return The Dai balance, the USDC balance, the ETH balance, the underlying
* Dai balance of the cDAI balance, the underlying USDC balance of the cUSDC
* balance, and the underlying ETH balance of the cEther balance.
*/
function getBalances() external returns (
uint256 daiBalance,
uint256 usdcBalance,
uint256 etherBalance,
uint256 cDaiUnderlyingDaiBalance,
uint256 cUsdcUnderlyingUsdcBalance,
uint256 cEtherUnderlyingEtherBalance
) {
daiBalance = _DAI.balanceOf(address(this));
usdcBalance = _USDC.balanceOf(address(this));
etherBalance = address(this).balance;
cDaiUnderlyingDaiBalance = _CDAI.balanceOfUnderlying(address(this));
cUsdcUnderlyingUsdcBalance = _CUSDC.balanceOfUnderlying(address(this));
cEtherUnderlyingEtherBalance = _CETH.balanceOfUnderlying(address(this));
}
/**
* @notice View function for getting the current user signing key for the
* smart wallet.
* @return The current user signing key.
*/
function getUserSigningKey() external view returns (address userSigningKey) {
userSigningKey = _userSigningKey;
}
/**
* @notice View function for getting the current nonce of the smart wallet.
* This nonce is incremented whenever an action is taken that requires a
* signature and/or a specific caller.
* @return The current nonce.
*/
function getNonce() external view returns (uint256 nonce) {
nonce = _nonce;
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by the key designated by the Dharma Key
* Registry in order to construct a valid signature for the corresponding
* action. The current nonce will be used, which means that it will only be
* valid for the next action taken.
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V4 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (4), USDCWithdrawal (5),
* ETHWithdrawal (6), DAIBorrow (7), and USDCBorrow (8).
* @param amount uint256 The amount to withdraw for Withdrawal actions, or 0
* for other action types.
* @param recipient address The account to transfer withdrawn funds to, the
* new user signing key, or the null address for cancelling.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getNextCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
action,
abi.encode(amount, recipient),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice View function that, given an action type and arguments, will return
* the action ID or message hash that will need to be prefixed (according to
* EIP-191 0x45), hashed, and signed by the key designated by the Dharma Key
* Registry in order to construct a valid signature for the corresponding
* action. Any nonce value may be supplied, which enables constructing valid
* message hashes for multiple future actions ahead of time.
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V4 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (4), USDCWithdrawal (5),
* ETHWithdrawal (6), DAIBorrow (7), and USDCBorrow (8).
* @param amount uint256 The amount to withdraw for Withdrawal actions, or 0
* for other action types.
* @param recipient address The account to transfer withdrawn funds to, the
* new user signing key, or the null address for cancelling.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function getCustomActionID(
ActionType action,
uint256 amount,
address recipient,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
action,
abi.encode(amount, recipient),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
function getNextGenericActionID(
address to,
bytes calldata data,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.Generic,
abi.encode(to, data),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
function getGenericActionID(
address to,
bytes calldata data,
uint256 nonce,
uint256 minimumActionGas
) external view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.Generic,
abi.encode(to, data),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice Pure function for getting the current Dharma Smart Wallet version.
* @return The current Dharma Smart Wallet version.
*/
function getVersion() external pure returns (uint256 version) {
version = _DHARMA_SMART_WALLET_VERSION;
}
// Note: this must currently be implemented as a public function (instead of
// as an external one) due to an ABIEncoderV2 `UnimplementedFeatureError`.
// Also note that the returned `ok` boolean only signifies that a call was
// successfully completed during execution - the call will be rolled back
// unless EVERY call succeeded and therefore the whole `ok` array is true.
function executeActionWithAtomicBatchCalls(
Call[] memory calls,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) public returns (bool[] memory ok, bytes[] memory returnData) {
// Ensure that each `to` address is a contract and is not this contract.
for (uint256 i = 0; i < calls.length; i++) {
_ensureValidGenericCallTarget(calls[i].to);
}
// Ensure caller and/or supplied signatures are valid and increment nonce.
(bytes32 actionID, uint256 nonce) = _validateActionAndIncrementNonce(
ActionType.GenericAtomicBatch,
abi.encode(calls),
minimumActionGas,
userSignature,
dharmaSignature
);
// Note: from this point on, there are no reverts (apart from out-of-gas or
// call-depth-exceeded) originating from this contract. However, one of the
// calls may revert, in which case the function will return `false`, along
// with the revert reason encoded as bytes, and fire an CallFailure event.
// Specify length of returned values in order to work with them in memory.
ok = new bool[](calls.length);
returnData = new bytes[](calls.length);
// Set self-call context to call _executeActionWithAtomicBatchCallsAtomic.
_selfCallContext = this.executeActionWithAtomicBatchCalls.selector;
// Make the atomic self-call - if any call fails, calls that preceded it
// will be rolled back and calls that follow it will not be made.
(bool externalOk, bytes memory rawCallResults) = address(this).call(
abi.encodeWithSelector(
this._executeActionWithAtomicBatchCallsAtomic.selector, calls
)
);
// Parse data returned from self-call into each call result and store / log.
CallReturn[] memory callResults = abi.decode(rawCallResults, (CallReturn[]));
for (uint256 i = 0; i < callResults.length; i++) {
Call memory currentCall = calls[i];
// Set the status and the return data / revert reason from the call.
ok[i] = callResults[i].ok;
returnData[i] = callResults[i].returnData;
// Emit CallSuccess or CallFailure event based on the outcome of the call.
if (callResults[i].ok) {
// Note: while the call succeeded, the action may still have "failed"
// (i.e. a successful calls to Compound can still return an error).
emit CallSuccess(
actionID,
!externalOk, // if another call failed this will have been rolled back
nonce,
currentCall.to,
currentCall.data,
callResults[i].returnData
);
} else {
// Note: while the call failed, the nonce will still be incremented,
// which will invalidate all supplied signatures.
emit CallFailure(
actionID,
nonce,
currentCall.to,
currentCall.data,
string(callResults[i].returnData)
);
// exit early - any calls after the first failed call will not execute.
break;
}
}
}
// Note: this must currently be implemented as a public function (instead of
// as an external one) due to an ABIEncoderV2 `UnimplementedFeatureError`
function _executeActionWithAtomicBatchCallsAtomic(
Call[] memory calls
) public returns (CallReturn[] memory callResults) {
// Ensure caller is this contract and self-call context is correctly set.
_enforceSelfCallFrom(this.executeActionWithAtomicBatchCalls.selector);
bool rollBack = false;
callResults = new CallReturn[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
// Perform low-level call and set return values using result.
(bool ok, bytes memory returnData) = calls[i].to.call(calls[i].data);
callResults[i] = CallReturn({ok: ok, returnData: returnData});
if (!ok) {
// exit early - any calls after the first failed call will not execute.
rollBack = true;
break;
}
}
if (rollBack) {
// wrap in length encoding and revert (provide data instead of a string)
bytes memory callResultsBytes = abi.encode(callResults);
assembly { revert(add(32, callResultsBytes), mload(callResultsBytes)) }
}
}
// cannot be implemented as an external function: `UnimplementedFeatureError`
function getNextGenericAtomicBatchActionID(
Call[] memory calls,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.GenericAtomicBatch,
abi.encode(calls),
_nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
// cannot be implemented as an external function: `UnimplementedFeatureError`
function getGenericAtomicBatchActionID(
Call[] memory calls,
uint256 nonce,
uint256 minimumActionGas
) public view returns (bytes32 actionID) {
// Determine the actionID - this serves as a signature hash for an action.
actionID = _getActionID(
ActionType.GenericAtomicBatch,
abi.encode(calls),
nonce,
minimumActionGas,
_userSigningKey,
_getDharmaSigningKey()
);
}
/**
* @notice Internal function for setting a new user signing key. A
* NewUserSigningKey event will also be emitted.
* @param userSigningKey address The new user signing key to set on this smart
* wallet.
*/
function _setUserSigningKey(address userSigningKey) internal {
// Ensure that a user signing key is set on this smart wallet.
require(userSigningKey != address(0), "No user signing key provided.");
_userSigningKey = userSigningKey;
emit NewUserSigningKey(userSigningKey);
}
/**
* @notice Internal function for incrementing the nonce.
*/
function _incrementNonce() internal {
_nonce++;
}
/**
* @notice Internal function for setting the allowance of a given ERC20 asset
* to the maximum value. This enables the corresponding cToken for the asset
* to pull in tokens in order to make deposits.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @return True if the approval succeeded, otherwise false.
*/
function _setFullApproval(AssetType asset) internal returns (bool ok) {
// Get asset's underlying token address and corresponding cToken address.
address token;
address cToken;
if (asset == AssetType.DAI) {
token = address(_DAI);
cToken = address(_CDAI);
} else {
token = address(_USDC);
cToken = address(_CUSDC);
}
// Approve cToken contract to transfer underlying on behalf of this wallet.
(ok, ) = token.call(abi.encodeWithSelector(
// Note: since both cTokens have the same interface, just use cDAI's.
_DAI.approve.selector, cToken, uint256(-1)
));
// Emit a corresponding event if the approval failed.
if (!ok) {
if (asset == AssetType.DAI) {
emit ExternalError(address(_DAI), "DAI contract reverted on approval.");
} else {
// Find out why USDC transfer reverted (it doesn't give revert reasons).
_diagnoseAndEmitUSDCSpecificError(_USDC.approve.selector);
}
}
}
/**
* @notice Internal function for depositing a given ERC20 asset and balance on
* the corresponding cToken. No value is returned, as no additional steps need
* to be conditionally performed after the deposit.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @param balance uint256 The amount of the asset to deposit. Note that an
* attempt to deposit "dust" (i.e. very small amounts) may result in 0 cTokens
* being minted, or in fewer cTokens being minted than is implied by the
* current exchange rate (due to lack of sufficient precision on the tokens).
*/
function _depositOnCompound(AssetType asset, uint256 balance) internal {
// Get cToken address for the asset type.
address cToken = asset == AssetType.DAI ? address(_CDAI) : address(_CUSDC);
// Attempt to mint the balance on the cToken contract.
(bool ok, bytes memory data) = cToken.call(abi.encodeWithSelector(
// Note: since both cTokens have the same interface, just use cDAI's.
_CDAI.mint.selector, balance
));
// Log an external error if something went wrong with the attempt.
_checkCompoundInteractionAndLogAnyErrors(
asset, _CDAI.mint.selector, ok, data
);
}
/**
* @notice Internal function for withdrawing a given underlying asset balance
* from the corresponding cToken. Note that the requested balance may not be
* currently available on Compound, which will cause the withdrawal to fail.
* @param asset uint256 The asset's ID, either Dai (0), USDC (1), or ETH (2).
* @param balance uint256 The amount of the asset to withdraw, denominated in
* the underlying token. Note that an attempt to withdraw "dust" (i.e. very
* small amounts) may result in 0 underlying tokens being redeemed, or in
* fewer tokens being redeemed than is implied by the current exchange rate
* (due to lack of sufficient precision on the tokens).
* @return True if the withdrawal succeeded, otherwise false.
*/
function _withdrawFromCompound(
AssetType asset,
uint256 balance
) internal returns (bool success) {
// Get cToken address for the asset type.
address cToken;
if (asset == AssetType.DAI) {
cToken = address(_CDAI);
} else { // Note: `else if` breaks code coverage.
if (asset == AssetType.USDC) {
cToken = address(_CUSDC);
} else {
cToken = address(_CETH);
}
}
// Attempt to redeem the underlying balance from the cToken contract.
(bool ok, bytes memory data) = cToken.call(abi.encodeWithSelector(
// Note: function selector is the same for each cToken so just use cDAI's.
_CDAI.redeemUnderlying.selector, balance
));
// Log an external error if something went wrong with the attempt.
success = _checkCompoundInteractionAndLogAnyErrors(
asset, _CDAI.redeemUnderlying.selector, ok, data
);
}
function _repayOnCompound(
AssetType asset,
uint256 balance
) internal returns (uint256 remainingBalance) {
// Get cToken address for the asset type. (ETH borrowing is not supported.)
address cToken = asset == AssetType.DAI ? address(_CDAI) : address(_CUSDC);
// TODO: handle errors originating from this call (reverts on MathError).
uint256 borrowBalance = CTokenInterface(cToken).borrowBalanceCurrent(
address(this)
);
// Skip repayment if there is no borrow balance.
if (borrowBalance == 0) {
return balance;
}
uint256 borrowBalanceToRepay;
if (borrowBalance > balance) {
borrowBalanceToRepay = balance;
} else {
borrowBalanceToRepay = borrowBalance;
}
// Note: SafeMath not needed since balance >= borrowBalanceToRepay
remainingBalance = balance - borrowBalanceToRepay;
// Attempt to repay the balance on the cToken contract.
(bool ok, bytes memory data) = cToken.call(abi.encodeWithSelector(
// Note: since both cTokens have the same interface, just use cDAI's.
_CDAI.repayBorrow.selector, borrowBalanceToRepay
));
// Log an external error if something went wrong with the attempt.
bool success = _checkCompoundInteractionAndLogAnyErrors(
asset, _CDAI.repayBorrow.selector, ok, data
);
// Reset remaining balance to initial balance if repay was not successful.
if (!success) {
remainingBalance = balance;
}
}
function _borrowFromCompound(
AssetType asset,
uint256 underlyingToBorrow
) internal returns (bool success) {
// Get cToken address for the asset type. (ETH borrowing is not supported.)
address cToken = asset == AssetType.DAI ? address(_CDAI) : address(_CUSDC);
// Attempt to borrow the underlying amount from the cToken contract.
(bool ok, bytes memory data) = cToken.call(abi.encodeWithSelector(
// Note: since both cTokens have the same interface, just use cDAI's.
_CDAI.borrow.selector, underlyingToBorrow
));
// Log an external error if something went wrong with the attempt.
success = _checkCompoundInteractionAndLogAnyErrors(
asset, _CDAI.borrow.selector, ok, data
);
}
function _depositEtherOnCompound() internal {
uint256 balance = address(this).balance;
if (balance > 0) {
// Attempt to mint the full ETH balance on the cEther contract.
(bool ok, bytes memory data) = address(_CETH).call.value(balance)(
abi.encodeWithSelector(_CETH.mint.selector)
);
// Log an external error if something went wrong with the attempt.
_checkCompoundInteractionAndLogAnyErrors(
AssetType.ETH, _CETH.mint.selector, ok, data
);
}
}
/**
* @notice Internal function for validating supplied gas (if specified),
* retrieving the signer's public key from the Dharma Key Registry, deriving
* the action ID, validating the provided caller and/or signatures using that
* action ID, and incrementing the nonce. This function serves as the
* entrypoint for all protected "actions" on the smart wallet, and is the only
* area where these functions should revert (other than due to out-of-gas
* errors, which can be guarded against by supplying a minimum action gas
* requirement).
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V4 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (4), USDCWithdrawal (5),
* ETHWithdrawal (6), DAIBorrow (7), and USDCBorrow (8).
* @param arguments bytes ABI-encoded arguments for the action.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used. A unique hash returned from `getCustomActionID` is prefixed
* and hashed to create the message hash for the signature.
* @param dharmaSignature bytes A signature that resolves to the public key
* returned for this account from the Dharma Key Registry. A unique hash
* returned from `getCustomActionID` is prefixed and hashed to create the
* signed message.
* @return The nonce of the current action (prior to incrementing it).
*/
function _validateActionAndIncrementNonce(
ActionType action,
bytes memory arguments,
uint256 minimumActionGas,
bytes memory userSignature,
bytes memory dharmaSignature
) internal returns (bytes32 actionID, uint256 actionNonce) {
// Ensure that the current gas exceeds the minimum required action gas.
// This prevents griefing attacks where an attacker can invalidate a
// signature without providing enough gas for the action to succeed. Also
// note that some gas will be spent before this check is reached - supplying
// ~30,000 additional gas should suffice when submitting transactions. To
// skip this requirement, supply zero for the minimumActionGas argument.
if (minimumActionGas != 0) {
require(
gasleft() >= minimumActionGas,
"Invalid action - insufficient gas supplied by transaction submitter."
);
}
// Get the current nonce for the action to be performed.
actionNonce = _nonce;
// Get the user signing key that will be used to verify their signature.
address userSigningKey = _userSigningKey;
// Get the Dharma signing key that will be used to verify their signature.
address dharmaSigningKey = _getDharmaSigningKey();
// Determine the actionID - this serves as the signature hash.
actionID = _getActionID(
action,
arguments,
actionNonce,
minimumActionGas,
userSigningKey,
dharmaSigningKey
);
// Compute the message hash - the hashed, EIP-191-0x45-prefixed action ID.
bytes32 messageHash = actionID.toEthSignedMessageHash();
// Actions other than Cancel require both signatures; Cancel only needs one.
if (action != ActionType.Cancel) {
// Validate user signing key signature unless it is `msg.sender`.
if (msg.sender != userSigningKey) {
require(
_validateUserSignature(
messageHash, action, arguments, userSigningKey, userSignature
),
"Invalid action - invalid user signature."
);
}
// Validate Dharma signing key signature unless it is `msg.sender`.
if (msg.sender != dharmaSigningKey) {
require(
dharmaSigningKey == messageHash.recover(dharmaSignature),
"Invalid action - invalid Dharma signature."
);
}
} else {
// Validate signing key signature unless user or Dharma is `msg.sender`.
if (msg.sender != userSigningKey && msg.sender != dharmaSigningKey) {
require(
dharmaSigningKey == messageHash.recover(dharmaSignature) ||
_validateUserSignature(
messageHash, action, arguments, userSigningKey, userSignature
),
"Invalid action - invalid signature."
);
}
}
// Increment nonce in order to prevent reuse of signatures after the call.
_incrementNonce();
}
/**
* @notice Internal function for entering cDAI, cUSDC, and cETH markets. This
* is performed now so that V0 smart wallets will not need to be reinitialized
* in order to support using these assets as collateral when borrowing funds.
*/
function _enterMarkets() internal {
// Create input array with each cToken address on which to enter a market.
address[] memory marketsToEnter = new address[](3);
marketsToEnter[0] = address(_CDAI);
marketsToEnter[1] = address(_CUSDC);
marketsToEnter[2] = address(_CETH);
// Attempt to enter each market by calling into the Comptroller contract.
(bool ok, bytes memory data) = address(_COMPTROLLER).call(
abi.encodeWithSelector(_COMPTROLLER.enterMarkets.selector, marketsToEnter)
);
// Log an external error if something went wrong with the attempt.
if (ok) {
uint256[] memory compoundErrors = abi.decode(data, (uint256[]));
for (uint256 i = 0; i < compoundErrors.length; i++) {
uint256 compoundError = compoundErrors[i];
if (compoundError != _COMPOUND_SUCCESS) {
emit ExternalError(
address(_COMPTROLLER),
string(
abi.encodePacked(
"Compound Comptroller contract returned error code ",
uint8((compoundError / 10) + 48),
uint8((compoundError % 10) + 48),
" while attempting to call enterMarkets."
)
)
);
}
}
} else {
// Decode the revert reason in the event one was returned.
string memory revertReason = _decodeRevertReason(data);
emit ExternalError(
address(_COMPTROLLER),
string(
abi.encodePacked(
"Compound Comptroller contract reverted on enterMarkets: ",
revertReason
)
)
);
}
}
/**
* @notice Internal function to determine whether a call to a given cToken
* succeeded, and to emit a relevant ExternalError event if it failed. The
* failure can be caused by a call that reverts, or by a call that does not
* revert but returns a non-zero error code.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @param functionSelector bytes4 The function selector that was called on the
* corresponding cToken of the asset type.
* @param ok bool A boolean representing whether the call returned or
* reverted.
* @param data bytes The data provided by the returned or reverted call.
* @return True if the interaction was successful, otherwise false. This will
* be used to determine if subsequent steps in the action should be attempted
* or not, specifically a transfer following a withdrawal.
*/
function _checkCompoundInteractionAndLogAnyErrors(
AssetType asset,
bytes4 functionSelector,
bool ok,
bytes memory data
) internal returns (bool success) {
// Log an external error if something went wrong with the attempt.
if (ok) {
uint256 compoundError = abi.decode(data, (uint256));
if (compoundError != _COMPOUND_SUCCESS) {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_getCTokenDetails(asset, functionSelector)
);
emit ExternalError(
account,
string(
abi.encodePacked(
"Compound ",
name,
" contract returned error code ",
uint8((compoundError / 10) + 48),
uint8((compoundError % 10) + 48),
" while attempting to call ",
functionName,
"."
)
)
);
} else {
success = true;
}
} else {
// Get called contract address, name of contract, and function name.
(address account, string memory name, string memory functionName) = (
_getCTokenDetails(asset, functionSelector)
);
// Decode the revert reason in the event one was returned.
string memory revertReason = _decodeRevertReason(data);
emit ExternalError(
account,
string(
abi.encodePacked(
"Compound ",
name,
" contract reverted while attempting to call ",
functionName,
": ",
revertReason
)
)
);
}
}
/**
* @notice Internal function to diagnose the reason that a withdrawal attempt
* failed and to emit a corresponding ExternalError event. Errors related to
* the call to `redeemUnderlying` on the cToken are handled by
* `_checkCompoundInteractionAndLogAnyErrors` - if the error did not originate
* from that call, it could be caused by a call to `balanceOfUnderlying` (i.e.
* when attempting a maximum withdrawal) or by the call to `transfer` on the
* underlying token after the withdrawal has been completed.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
*/
function _diagnoseAndEmitErrorRelatedToWithdrawal(AssetType asset) internal {
// Get called contract address and name of contract (no need for selector).
(address cToken, string memory name, ) = _getCTokenDetails(
asset, bytes4(0)
);
// Revert could be caused by cToken MathError or underlying transfer error.
(bool check, ) = cToken.call(abi.encodeWithSelector(
// Note: since both cTokens have the same interface, just use cDAI's.
_CDAI.balanceOfUnderlying.selector, address(this)
));
if (!check) {
emit ExternalError(
cToken,
string(
abi.encodePacked(
name, " contract reverted on call to balanceOfUnderlying."
)
)
);
} else {
if (asset == AssetType.DAI) {
emit ExternalError(address(_DAI), "DAI contract reverted on transfer.");
} else { // Note: `else if` breaks code coverage.
if (asset == AssetType.ETH) {
// Note: this should log the address of the recipient.
emit ExternalError(address(this), "ETH transfer reverted.");
} else {
// Find out why USDC transfer reverted (doesn't give revert reasons).
_diagnoseAndEmitUSDCSpecificError(_USDC.transfer.selector);
}
}
}
}
/**
* @notice Internal function to diagnose the reason that a call to the USDC
* contract failed and to emit a corresponding ExternalError event. USDC can
* blacklist accounts and pause the contract, which can both cause a transfer
* or approval to fail.
* @param functionSelector bytes4 The function selector that was called on the
* USDC contract.
*/
function _diagnoseAndEmitUSDCSpecificError(bytes4 functionSelector) internal {
// Determine the name of the function that was called on USDC.
string memory functionName;
if (functionSelector == _USDC.transfer.selector) {
functionName = "transfer";
} else {
functionName = "approve";
}
// Find out why USDC transfer reverted (it doesn't give revert reasons).
if (_USDC_NAUGHTY.isBlacklisted(address(this))) {
emit ExternalError(
address(_USDC),
string(
abi.encodePacked(
functionName, " failed - USDC has blacklisted this user."
)
)
);
} else { // Note: `else if` breaks coverage.
if (_USDC_NAUGHTY.paused()) {
emit ExternalError(
address(_USDC),
string(
abi.encodePacked(
functionName, " failed - USDC contract is currently paused."
)
)
);
} else {
emit ExternalError(
address(_USDC),
string(
abi.encodePacked(
"USDC contract reverted on ", functionName, "."
)
)
);
}
}
}
/**
* @notice Internal function to ensure that protected functions can only be
* called from this contract and that they have the appropriate context set.
* The self-call context is then cleared. It is used as an additional guard
* against reentrancy, especially once generic actions are supported by the
* smart wallet in future versions.
* @param selfCallContext bytes4 The expected self-call context, equal to the
* function selector of the approved calling function.
*/
function _enforceSelfCallFrom(bytes4 selfCallContext) internal {
// Ensure caller is this contract and self-call context is correctly set.
require(
msg.sender == address(this) &&
_selfCallContext == selfCallContext,
"External accounts or unapproved internal functions cannot call this."
);
// Clear the self-call context.
delete _selfCallContext;
}
/**
* @notice Internal view function for validating a user's signature. If the
* user's signing key does not have contract code, it will be validated via
* ecrecover; otherwise, it will be validated using ERC-1271, passing the
* message hash that was signed, the action type, and the arguments as data.
* @param messageHash bytes32 The message hash that is signed by the user. It
* is derived by prefixing (according to EIP-191 0x45) and hashing an actionID
* returned from `getCustomActionID`.
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V4 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (4), USDCWithdrawal (5),
* ETHWithdrawal (6), DAIBorrow (7), and USDCBorrow (8).
* @param arguments bytes ABI-encoded arguments for the action.
* @param userSignature bytes A signature that resolves to the public key
* set for this account in storage slot zero, `_userSigningKey`. If the user
* signing key is not a contract, ecrecover will be used; otherwise, ERC1271
* will be used.
* @return A boolean representing the validity of the supplied user signature.
*/
function _validateUserSignature(
bytes32 messageHash,
ActionType action,
bytes memory arguments,
address userSigningKey,
bytes memory userSignature
) internal view returns (bool valid) {
if (!userSigningKey.isContract()) {
valid = userSigningKey == messageHash.recover(userSignature);
} else {
bytes memory data = abi.encode(messageHash, action, arguments);
valid = (
ERC1271(userSigningKey).isValidSignature(
data, userSignature
) == _ERC_1271_MAGIC_VALUE
);
}
}
/**
* @notice Internal view function to get the Dharma signing key for the smart
* wallet from the Dharma Key Registry. This key can be set for each specific
* smart wallet - if none has been set, a global fallback key will be used.
* @return The address of the Dharma signing key, or public key corresponding
* to the secondary signer.
*/
function _getDharmaSigningKey() internal view returns (
address dharmaSigningKey
) {
dharmaSigningKey = _DHARMA_KEY_REGISTRY.getKey();
}
/**
* @notice Internal view function that, given an action type and arguments,
* will return the action ID or message hash that will need to be prefixed
* (according to EIP-191 0x45), hashed, and signed by the key designated by
* the Dharma Key Registry in order to construct a valid signature for the
* corresponding action. The current nonce will be supplied to this function
* when reconstructing an action ID during protected function execution based
* on the supplied parameters.
* @param action uint8 The type of action, designated by it's index. Valid
* actions in V4 include Cancel (0), SetUserSigningKey (1), Generic (2),
* GenericAtomicBatch (3), DAIWithdrawal (4), USDCWithdrawal (5),
* ETHWithdrawal (6), DAIBorrow (7), and USDCBorrow (8).
* @param arguments bytes ABI-encoded arguments for the action.
* @param nonce uint256 The nonce to use.
* @param minimumActionGas uint256 The minimum amount of gas that must be
* provided to this call - be aware that additional gas must still be included
* to account for the cost of overhead incurred up until the start of this
* function call.
* @param dharmaSigningKey address The address of the secondary key, or public
* key corresponding to the secondary signer.
* @return The action ID, which will need to be prefixed, hashed and signed in
* order to construct a valid signature.
*/
function _getActionID(
ActionType action,
bytes memory arguments,
uint256 nonce,
uint256 minimumActionGas,
address userSigningKey,
address dharmaSigningKey
) internal view returns (bytes32 actionID) {
// The actionID is constructed according to EIP-191-0x45 to prevent replays.
actionID = keccak256(
abi.encodePacked(
address(this),
_DHARMA_SMART_WALLET_VERSION,
userSigningKey,
dharmaSigningKey,
nonce,
minimumActionGas,
action,
arguments
)
);
}
/**
* @notice Internal pure function to get the cToken address, it's name, and
* the name of the called function, based on a supplied asset type and
* function selector. It is used to help construct ExternalError events.
* @param asset uint256 The ID of the asset, either Dai (0) or USDC (1).
* @param functionSelector bytes4 The function selector that was called on the
* corresponding cToken of the asset type.
* @return The cToken address, it's name, and the name of the called function.
*/
function _getCTokenDetails(
AssetType asset,
bytes4 functionSelector
) internal pure returns (
address account,
string memory name,
string memory functionName
) {
if (asset == AssetType.DAI) {
account = address(_CDAI);
name = "cDAI";
} else { // Note: `else if` breaks code coverage.
if (asset == AssetType.USDC) {
account = address(_CUSDC);
name = "cUSDC";
} else {
account = address(_CETH);
name = "cEther";
}
}
// Note: since both cTokens have the same interface, just use cDAI's.
if (functionSelector == _CDAI.mint.selector) {
functionName = "mint";
} else { // Note: `else if` breaks code coverage.
if (functionSelector == _CDAI.redeemUnderlying.selector) {
functionName = "redeemUnderlying";
} else {
if (functionSelector == _CDAI.borrow.selector) {
functionName = "borrow";
} else {
functionName = "repayBorrow";
}
}
}
}
/**
* @notice Internal pure function to ensure that a given `to` address provided
* as part of a generic action is valid. Calls cannot be performed to accounts
* without code or back into the smart wallet itself.
*/
function _ensureValidGenericCallTarget(address to) internal view {
require(
to.isContract(),
"Invalid `to` parameter - must supply a contract address containing code."
);
require(
to != address(this),
"Invalid `to` parameter - cannot supply the address of this contract."
);
}
/**
* @notice Internal pure function to decode revert reasons. The revert reason
* prefix is removed and the remaining string argument is decoded.
* @param revertData bytes The raw data supplied alongside the revert.
* @return The decoded revert reason string.
*/
function _decodeRevertReason(
bytes memory revertData
) internal pure returns (string memory revertReason) {
// Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector
if (
revertData.length > 68 && // prefix (4) + position (32) + length (32)
revertData[0] == byte(0x08) &&
revertData[1] == byte(0xc3) &&
revertData[2] == byte(0x79) &&
revertData[3] == byte(0xa0)
) {
// Get the revert reason without the prefix from the revert data.
bytes memory revertReasonBytes = new bytes(revertData.length - 4);
for (uint256 i = 4; i < revertData.length; i++) {
revertReasonBytes[i - 4] = revertData[i];
}
// Decode the resultant revert reason as a string.
revertReason = abi.decode(revertReasonBytes, (string));
} else {
// Simply return the default, with no revert reason.
revertReason = "(no revert reason)";
}
}
} | * @notice Withdraw Dai to a provided recipient address by redeeming the underlying Dai from the cDAI contract and transferring it to the recipient. All Dai in Compound and in the smart wallet itself can be withdrawn by providing an amount of uint256(-1) or 0xfff...fff. This function can be called directly by the account set as the global key on the Dharma Key Registry, or by any relayer that provides a signed message from the same keyholder. The nonce used for the signature must match the current nonce on the smart wallet, and gas supplied to the call must exceed the specified minimum action gas, plus the gas that will be spent before the gas check is reached - usually somewhere around 25,000 gas. If the withdrawal fails, an ExternalError with additional details on what went wrong will be emitted. Note that some dust may still be left over, even in the event of a max withdrawal, due to the fact that Dai has a higher precision than cDAI. Also note that the withdrawal will fail in the event that Compound does not have sufficient Dai available to withdraw. @param amount uint256 The amount of Dai to withdraw. @param recipient address The account to transfer the withdrawn Dai to. @param minimumActionGas uint256 The minimum amount of gas that must be provided to this call - be aware that additional gas must still be included to account for the cost of overhead incurred up until the start of this function call. @param userSignature bytes A signature that resolves to the public key set for this account in storage slot zero, `_userSigningKey`. If the user signing key is not a contract, ecrecover will be used; otherwise, ERC1271 will be used. A unique hash returned from `getCustomActionID` is prefixed and hashed to create the message hash for the signature. @param dharmaSignature bytes A signature that resolves to the public key returned for this account from the Dharma Key Registry. A unique hash returned from `getCustomActionID` is prefixed and hashed to create the signed message. @return True if the withdrawal succeeded, otherwise false./ Ensure caller and/or supplied signatures are valid and increment nonce. Set the self-call context so we can call _withdrawDaiAtomic. Make the atomic self-call - if redeemUnderlying fails on cDAI, it will succeed but nothing will happen except firing an ExternalError event. If the second part of the self-call (the Dai transfer) fails, it will revert and roll back the first part of the call, and we'll fire an ExternalError event after returning from the failed call. If the atomic call failed, diagnose the reason and emit an event. This revert could be caused by cDai MathError or Dai transfer error. Set ok to false if the call succeeded but the withdrawal failed. | function withdrawDai(
uint256 amount,
address recipient,
uint256 minimumActionGas,
bytes calldata userSignature,
bytes calldata dharmaSignature
) external returns (bool ok) {
_validateActionAndIncrementNonce(
ActionType.DAIWithdrawal,
abi.encode(amount, recipient),
minimumActionGas,
userSignature,
dharmaSignature
);
_selfCallContext = this.withdrawDai.selector;
bytes memory returnData;
(ok, returnData) = address(this).call(abi.encodeWithSelector(
this._withdrawDaiAtomic.selector, amount, recipient
));
if (!ok) {
_diagnoseAndEmitErrorRelatedToWithdrawal(AssetType.DAI);
ok = abi.decode(returnData, (bool));
}
}
| 12,781,666 | [
1,
1190,
9446,
463,
10658,
358,
279,
2112,
8027,
1758,
635,
283,
24903,
310,
326,
6808,
463,
10658,
628,
326,
276,
9793,
45,
6835,
471,
906,
74,
20245,
518,
358,
326,
8027,
18,
4826,
463,
10658,
316,
21327,
471,
316,
326,
13706,
9230,
6174,
848,
506,
598,
9446,
82,
635,
17721,
392,
3844,
434,
2254,
5034,
19236,
21,
13,
578,
374,
5297,
74,
2777,
25449,
18,
1220,
445,
848,
506,
2566,
5122,
635,
326,
2236,
444,
487,
326,
2552,
498,
603,
326,
463,
30250,
2540,
1929,
5438,
16,
578,
635,
1281,
1279,
1773,
716,
8121,
279,
6726,
883,
628,
326,
1967,
498,
4505,
18,
1021,
7448,
1399,
364,
326,
3372,
1297,
845,
326,
783,
7448,
603,
326,
13706,
9230,
16,
471,
16189,
4580,
358,
326,
745,
1297,
9943,
326,
1269,
5224,
1301,
16189,
16,
8737,
326,
16189,
716,
903,
506,
26515,
1865,
326,
16189,
866,
353,
8675,
300,
11234,
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,
225,
445,
598,
9446,
40,
10658,
12,
203,
565,
2254,
5034,
3844,
16,
203,
565,
1758,
8027,
16,
203,
565,
2254,
5034,
5224,
1803,
27998,
16,
203,
565,
1731,
745,
892,
729,
5374,
16,
203,
565,
1731,
745,
892,
11007,
297,
2540,
5374,
203,
225,
262,
3903,
1135,
261,
6430,
1529,
13,
288,
203,
565,
389,
5662,
1803,
1876,
10798,
13611,
12,
203,
1377,
4382,
559,
18,
9793,
45,
1190,
9446,
287,
16,
203,
1377,
24126,
18,
3015,
12,
8949,
16,
8027,
3631,
203,
1377,
5224,
1803,
27998,
16,
203,
1377,
729,
5374,
16,
203,
1377,
11007,
297,
2540,
5374,
203,
565,
11272,
203,
203,
565,
389,
2890,
22582,
273,
333,
18,
1918,
9446,
40,
10658,
18,
9663,
31,
203,
203,
565,
1731,
3778,
327,
751,
31,
203,
565,
261,
601,
16,
327,
751,
13,
273,
1758,
12,
2211,
2934,
1991,
12,
21457,
18,
3015,
1190,
4320,
12,
203,
1377,
333,
6315,
1918,
9446,
40,
10658,
23102,
18,
9663,
16,
3844,
16,
8027,
203,
565,
262,
1769,
203,
203,
565,
309,
16051,
601,
13,
288,
203,
1377,
389,
12264,
2135,
307,
1876,
17982,
668,
8017,
774,
1190,
9446,
287,
12,
6672,
559,
18,
9793,
45,
1769,
203,
1377,
1529,
273,
24126,
18,
3922,
12,
2463,
751,
16,
261,
6430,
10019,
203,
565,
289,
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
] |
./full_match/4/0xDDF38E76F79794e7D17C221Cc19BAA12F497aE7B/sources/contracts/DefiYieldToken.sol | * @dev Returns the downcasted int64 from int256, reverting on overflow (when the input is less than smallest int64 or greater than largest int64). Counterpart to Solidity's `int64` operator. Requirements: - input must fit into 64 bits _Available since v3.1._/ | function toInt64(int256 value) internal pure returns (int64) {
require(
value >= type(int64).min && value <= type(int64).max,
"SafeCast: value doesn't fit in 64 bits"
);
return int64(value);
}
| 728,053 | [
1,
1356,
326,
2588,
4155,
329,
509,
1105,
628,
509,
5034,
16,
15226,
310,
603,
9391,
261,
13723,
326,
810,
353,
5242,
2353,
13541,
509,
1105,
578,
6802,
2353,
12756,
509,
1105,
2934,
9354,
2680,
358,
348,
7953,
560,
1807,
1375,
474,
1105,
68,
3726,
18,
29076,
30,
300,
810,
1297,
4845,
1368,
5178,
4125,
389,
5268,
3241,
331,
23,
18,
21,
6315,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
20771,
1105,
12,
474,
5034,
460,
13,
2713,
16618,
1135,
261,
474,
1105,
13,
288,
203,
3639,
2583,
12,
203,
5411,
460,
1545,
618,
12,
474,
1105,
2934,
1154,
597,
460,
1648,
618,
12,
474,
1105,
2934,
1896,
16,
203,
5411,
315,
9890,
9735,
30,
460,
3302,
1404,
4845,
316,
5178,
4125,
6,
203,
3639,
11272,
203,
3639,
327,
509,
1105,
12,
1132,
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
] |
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@nomiclabs/buidler/console.sol";
import "./ILBCR.sol";
contract LBCR is Ownable, ILBCR {
address[] authorisedContracts;
uint256 _decimals; // decimals to calculate collateral factor
// Implementation of L = (lower, upper, factor)
mapping (uint256 => uint[]) _layers; // array of layers, e.g. {1,2,3,4}
mapping (uint256 => mapping (uint256 => uint256)) _lower; // versioned lower bound of layer
mapping (uint256 => mapping (uint256 => uint256)) _upper; // versioned upper bound of layer
mapping (uint256 => mapping (uint256 => uint256)) _factors; // versioned factor of layer
mapping (uint256 => mapping (uint256 => uint256)) _rewards; // versioned reward (score) for performing an action
mapping(address => uint256) compatibilityScores;
mapping(address => uint256) compatibilityScoreVersions;
mapping(address => bool) maintainCompatibilityScoreOnUpdate;
uint256 _latestVersion;
uint256 _currentVersion;
// Implementation of the registry
mapping (uint256 => mapping (address => uint256)) _assignments; // layer assignment by round and agent
mapping (uint256 => mapping (address => uint256)) _scores; // score by round and agent
mapping (address => uint256) _interactionCount;
uint256 _round; // current round in the protocol
mapping (address => bool) _agents; // track all agents
address[] agentList;
uint256 _blockperiod; // block period until curation
uint256 _start; // start of period
uint256 _end; // end of period
mapping(address => uint256) timeDiscountedFactors;
uint256 recentFactorTimeDiscount;
uint256 olderFactorTimeDiscount;
constructor() public {
addAuthorisedContract(msg.sender);
_decimals = 3; // e.g. a factor of 1500 is equal to 1.5 times the collateral
_round = 0; // init rounds
_blockperiod = 10; // wait for 10 blocks to curate
_start = block.number;
_end = block.number + _blockperiod;
recentFactorTimeDiscount = 400;
olderFactorTimeDiscount = 600;
_latestVersion = 1;
_currentVersion = 0;
}
function addAuthorisedContract(address authorisedContract) public onlyAuthorised {
authorisedContracts.push(authorisedContract);
}
modifier onlyAuthorised() {
bool isAuthorised = false;
if(isOwner()) {
isAuthorised = true;
}
for (uint i = 0; i < authorisedContracts.length; i++) {
if(authorisedContracts[i] == msg.sender) {
isAuthorised = true;
break;
}
}
require(isAuthorised == true, "Caller is not authorised to perform this action");
_;
}
/// @notice Returns a number between 0 and 100 representing the compatibility score between the current LBCR and the
/// LBCRs of `protocol`. If no score was set for `protocol`, returns 0
/// @param protocol Retrieve the compatibility between this protocol and `protocol`
function getCompatibilityScoreWith(address protocol) external view returns (uint256) {
if(protocol == address(this)) {
return 100;
}
if(_currentVersion == compatibilityScoreVersions[protocol] || maintainCompatibilityScoreOnUpdate[protocol]) {
return compatibilityScores[protocol];
}
return 0;
}
/// @notice Set a number between 0 and 100 representing the compatibility score between the current LBCR and the
/// LBCRs of `protocol`. When a new compatibility score is set, the `maintainCompatibilityScoreOnUpdate[protocol]`
/// is automatically set to `true` (such that when `protocol` update their LBCR version, the compatibility score
/// set now is maintained)
/// @param protocol Address of `protocol`'s LBCR to set compatibility score with
/// @param score Compatibility score
function setCompatibilityScoreWith(address protocol, uint256 score) external onlyAuthorised {
require(score >= 0 && score <= 100, "score must be a number between 0 and 100");
compatibilityScores[protocol] = score;
compatibilityScoreVersions[protocol] = _latestVersion;
maintainCompatibilityScoreOnUpdate[protocol] = true;
}
/// @notice Update the `maintainCompatibilityScoreOnUpdate` map with respect to `protocol`. A `true` value means that
/// if `protocol` update their LBCR version, the current protocol trusts that the update will not be disruptive and
/// the compatiblity score should remain the same. A `false` value means that new updates to the LBCR of `protocol`
/// are untrusted and the compatibility score will default to zero
function setMaintainCompatibilityScoreOnUpdate(bool maintainCompatibilityScoreOnUpdateValue, address protocol) external onlyAuthorised {
maintainCompatibilityScoreOnUpdate[protocol] = maintainCompatibilityScoreOnUpdateValue;
}
function getMaintainCompatibilityScoreOnUpdate(address protocol) external view returns (bool) {
return maintainCompatibilityScoreOnUpdate[protocol];
}
/// @notice Increment `_latestVersion` to start setting parameters of a new LBCR version
function incrementLatestVersion() external onlyAuthorised {
_latestVersion += 1;
}
/// @notice Upgrade the LBCR to a new version by setting `_currentVersion` (the variable used to index the version
/// parameter maps) to `_latestVersion`
function upgradeVersion() external onlyAuthorised {
curateIfRoundEnded();
_currentVersion = _latestVersion;
}
// ##############
// ### LAYERS ###
// ##############
function getLayers() public view returns(uint[] memory) {
return _layers[_currentVersion];
}
/// @notice Set layer indexes
function setLayers(uint8[] memory layers) public onlyAuthorised {
// set layers
_layers[_latestVersion] = layers;
}
/// @notice Reset layer indexes
function resetLayers() external onlyAuthorised {
delete _layers[_currentVersion];
}
/// @notice Add a new index to the array of layer indexes
function addLayer(uint layer) external onlyAuthorised {
_layers[_latestVersion].push(layer);
}
// ##############
// ### FACTOR ###
// ##############
/// @notice Get time discounted agent factor (a value between 0 and 1),
/// representing the discounted collateral `agent` should pay
function getAgentFactor(address agent) public view returns (uint256) {
uint assignment = getAssignment(agent);
require(assignment > 0, "agent not assigned to layer");
return timeDiscountedFactors[agent];
}
/// @notice Get the `layer` factor that the agent is currently in. Usage of this function is discouraged,
/// as `getAgentFactor` provides better game theoretic incentives to behave well
function getFactor(uint layer) public view returns (uint256) {
return _factors[_currentVersion][layer];
}
/// @notice Set the collateralisation `factor` of a `layer` index. The `factor` is a value between 0 and 1
function setFactor(uint layer, uint256 factor) public onlyAuthorised {
require(_latestVersion != _currentVersion, "LatestVersion must be incremented before updating");
_factors[_latestVersion][layer] = factor;
}
// ###############
// ### REWARD ###
// ###############
/// @return reward The score an agent receives after performing a certain action. Assumes actions have fixed rewards.
function getReward(uint256 action) public view returns (uint256) {
return _rewards[_currentVersion][action];
}
/// @notice Set the `reward` for a certain `action`
function setReward(uint256 action, uint256 reward) public onlyAuthorised returns (bool) {
require(_latestVersion != _currentVersion, "LatestVersion must be incremented before updating");
_rewards[_latestVersion][action] = reward;
return true;
}
// ###############
// ### BOUNDS ###
// ###############
/// @notice Get the pair (`lowerScoreBound`, `upperScoreBound`) representing the criteria for demoting or
/// promoting an agent in the LBCR
function getBounds(uint layer) public view returns (uint256, uint256) {
return (_lower[_currentVersion][layer], _upper[_currentVersion][layer]);
}
/// @notice Given a `layer` index, set the pair (`lowerScoreBound`, `upperScoreBound`) representing the
/// criteria for demoting or promoting an agent in the LBCR
function setBounds(uint layer, uint256 lower, uint256 upper) public onlyAuthorised returns (bool) {
_lower[_currentVersion][layer] = lower;
_upper[_currentVersion][layer] = upper;
emit NewBound(lower, upper);
return true;
}
event NewBound(uint256 lower, uint256 upper);
// ######################
// ### AGENT REGISTRY ###
// ######################
/// @notice Get layer index representing the assignment of `agent` in the current LBCR round
function getAssignment(address agent) public view returns(uint assignment) {
// check if agent is registered
if (_agents[agent]) {
// check if agent is assigned to a layer in the current round
if (_assignments[_round][agent] == 0) {
// check if the agent was assigned to a layer in previous rounds
for (uint i = 1; i < _layers[_currentVersion].length && i < _round; i++) {
if (_assignments[_round - i][agent] > i) {
return _assignments[_round - i][agent] - i;
}
}
return 1;
} else {
return _assignments[_round][agent];
}
} else {
return 0;
}
}
/// @notice Get the score of `agent` in the current LBCR round
function getScore(address agent) public view returns (uint256) {
uint assignment = getAssignment(agent);
require(assignment > 0, "agent not assigned to layer");
return _scores[_round][agent];
}
/// @notice Get the number of actions performed by `agent` since joining the LBCR
function getInteractionCount(address agent) public view returns (uint256) {
return _interactionCount[agent];
}
/// @notice Sign `agent` up to the LBCR. They are initially assigned to the first layer
function registerAgent(address agent) external onlyAuthorised returns (bool) {
curateIfRoundEnded();
// register agent
_agents[agent] = true;
// asign agent to lowest layer
_assignments[_round][agent] = _layers[_currentVersion][0];
// update the score of the agent
_scores[_round][agent] += _rewards[_currentVersion][0];
timeDiscountedFactors[agent] = _factors[_currentVersion][_assignments[_round][agent]];
agentList.push(agent);
emit RegisterAgent(agent);
return true;
}
event RegisterAgent(address agent);
// ####################
// ### TCR CONTROLS ###
// ####################
/// @notice Update the score of `agent` given they have performed the action encoded as `action`
function update(address agent, uint256 action) external onlyAuthorised {
curateIfRoundEnded();
_scores[_round][agent] += _rewards[_currentVersion][action];
// asignment in the current round
uint assignment = getAssignment(agent);
require(assignment > 0, "agent not assigned to layer");
_interactionCount[agent] += 1;
// promote the agent to the next layer
if (_scores[_round][agent] >= _upper[_currentVersion][assignment] && assignment != _layers[_currentVersion].length) {
// asignment in the next round
_assignments[_round + 1][agent] = assignment + 1;
// demote the agent to the previous layer
} else if (_scores[_round][agent] <= _lower[_currentVersion][assignment] && assignment > 1) {
// asignment in the next round
_assignments[_round + 1][agent] = assignment - 1;
// agent layer remans the same
} else {
_assignments[_round + 1][agent] = assignment;
}
emit Update(agent, _rewards[_currentVersion][action], _scores[_round][agent]);
}
// function computeReward(uint256 action, uint256 amountInETH) private returns (uint256) {
// }
event Update(address agent, uint256 reward, uint256 score);
/// @notice If `_blockperiod` blocks have elapsed since the current round started, the round will end
/// and agents will be curated into new layer positions
function curateIfRoundEnded() public {
// anyone can call this function, to ensure curation happens at the right time
if(_start != 0 && block.number >= _end) {
curate();
}
}
/// @notice Actual curating function. Updates agent assignments to layers by calling `updateTimeDiscountedFactors`
function curate() private returns (bool) {
require(_start != 0, "period not started");
require(block.number >= _end, "period not ended");
// update start and end times for next round
_start = block.number;
_end = block.number + _blockperiod;
// switch to the next round
_round++;
updateTimeDiscountedFactors();
emit Curate(_round, _start, _end);
return true;
}
/// @notice For every user in the LBCR, given the current layer assignment, compute their time-discounted factor
/// (i.e. their game theory backed factor), which represents the discounted collateral amount the agent should pay
function updateTimeDiscountedFactors() private {
for(uint i = 0; i < agentList.length; i++) {
uint assignment = getAssignment(agentList[i]);
timeDiscountedFactors[agentList[i]] = (_factors[_currentVersion][assignment] * recentFactorTimeDiscount + timeDiscountedFactors[agentList[i]] * olderFactorTimeDiscount) / (10 ** _decimals);
}
}
event Curate(uint256 round, uint256 start, uint256 end);
} | @notice Get layer index representing the assignment of `agent` in the current LBCR round check if agent is registered check if agent is assigned to a layer in the current round check if the agent was assigned to a layer in previous rounds | function getAssignment(address agent) public view returns(uint assignment) {
if (_agents[agent]) {
if (_assignments[_round][agent] == 0) {
for (uint i = 1; i < _layers[_currentVersion].length && i < _round; i++) {
if (_assignments[_round - i][agent] > i) {
return _assignments[_round - i][agent] - i;
}
}
return 1;
return _assignments[_round][agent];
}
return 0;
}
}
| 14,042,784 | [
1,
967,
3018,
770,
5123,
326,
6661,
434,
1375,
5629,
68,
316,
326,
783,
511,
38,
5093,
3643,
866,
309,
4040,
353,
4104,
866,
309,
4040,
353,
6958,
358,
279,
3018,
316,
326,
783,
3643,
866,
309,
326,
4040,
1703,
6958,
358,
279,
3018,
316,
2416,
21196,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
7729,
12,
2867,
4040,
13,
1071,
1476,
1135,
12,
11890,
6661,
13,
288,
203,
3639,
309,
261,
67,
23560,
63,
5629,
5717,
288,
203,
5411,
309,
261,
67,
24326,
63,
67,
2260,
6362,
5629,
65,
422,
374,
13,
288,
203,
7734,
364,
261,
11890,
277,
273,
404,
31,
277,
411,
389,
10396,
63,
67,
2972,
1444,
8009,
2469,
597,
277,
411,
389,
2260,
31,
277,
27245,
288,
203,
10792,
309,
261,
67,
24326,
63,
67,
2260,
300,
277,
6362,
5629,
65,
405,
277,
13,
288,
203,
13491,
327,
389,
24326,
63,
67,
2260,
300,
277,
6362,
5629,
65,
300,
277,
31,
203,
10792,
289,
203,
7734,
289,
203,
7734,
327,
404,
31,
203,
7734,
327,
389,
24326,
63,
67,
2260,
6362,
5629,
15533,
203,
5411,
289,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.19;
// File: contracts/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || 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;
}
}
// File: contracts/Owned.sol
contract Owned {
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
// owner address to enable admin functions
mapping (address => bool) public isOwner;
address[] public owners;
address public operator;
modifier onlyOwner {
require(isOwner[msg.sender]);
_;
}
modifier onlyOperator {
require(msg.sender == operator);
_;
}
function setOperator(address _operator) external onlyOwner {
require(_operator != address(0));
operator = _operator;
}
function removeOwner(address _owner) public onlyOwner {
require(owners.length > 1);
isOwner[_owner] = false;
for (uint i = 0; i < owners.length - 1; i++) {
if (owners[i] == _owner) {
owners[i] = owners[SafeMath.sub(owners.length, 1)];
break;
}
}
owners.length = SafeMath.sub(owners.length, 1);
OwnerRemoval(_owner);
}
function addOwner(address _owner) external onlyOwner {
require(_owner != address(0));
if(isOwner[_owner]) return;
isOwner[_owner] = true;
owners.push(_owner);
OwnerAddition(_owner);
}
function setOwners(address[] _owners) internal {
for (uint i = 0; i < _owners.length; i++) {
require(_owners[i] != address(0));
isOwner[_owners[i]] = true;
OwnerAddition(_owners[i]);
}
owners = _owners;
}
function getOwners() public constant returns (address[]) {
return owners;
}
}
// File: contracts/Token.sol
// Abstract contract for the full ERC 20 Token standard
// https://github.com/ethereum/EIPs/issues/20
pragma solidity ^0.4.19;
contract Token {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public constant returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
// File: contracts/StandardToken.sol
/*
You should inherit from StandardToken or, for a token like you would want to
deploy in something like Mist, see HumanStandardToken.sol.
(This implements ONLY the standard functions and NOTHING else.
If you deploy this, you won't have anything useful.)
Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/issues/20
.*/
pragma solidity ^0.4.19;
contract StandardToken is Token {
function transfer(address _to, uint256 _value) public returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
//require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
//same as above. Replace this line with the following if you want to protect against wrapping uints.
//require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]);
require(balances[_from] >= _value && allowed[_from][msg.sender] >= _value);
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
// File: contracts/Validating.sol
contract Validating {
modifier validAddress(address _address) {
require(_address != address(0x0));
_;
}
modifier notZero(uint _number) {
require(_number != 0);
_;
}
modifier notEmpty(string _string) {
require(bytes(_string).length != 0);
_;
}
}
// File: contracts/Fee.sol
/**
* @title FEE is an ERC20 token used to pay for trading on the exchange.
* For deeper rational read https://leverj.io/whitepaper.pdf.
* FEE tokens do not have limit. A new token can be generated by owner.
*/
contract Fee is Owned, Validating, StandardToken {
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint256 value);
string public name; //fancy name: eg Simon Bucks
uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether.
string public symbol; //An identifier: eg SBX
string public version = 'F0.2'; //human 0.1 standard. Just an arbitrary versioning scheme.
address public minter;
modifier onlyMinter {
require(msg.sender == minter);
_;
}
/// @notice Constructor to set the owner, tokenName, decimals and symbol
function Fee(
address[] _owners,
string _tokenName,
uint8 _decimalUnits,
string _tokenSymbol
)
public
notEmpty(_tokenName)
notEmpty(_tokenSymbol)
{
setOwners(_owners);
name = _tokenName;
decimals = _decimalUnits;
symbol = _tokenSymbol;
}
/// @notice To set a new minter address
/// @param _minter The address of the minter
function setMinter(address _minter) external onlyOwner validAddress(_minter) {
minter = _minter;
}
/// @notice To eliminate tokens and adjust the price of the FEE tokens
/// @param _value Amount of tokens to delete
function burnTokens(uint _value) public notZero(_value) {
require(balances[msg.sender] >= _value);
balances[msg.sender] = SafeMath.sub(balances[msg.sender], _value);
totalSupply = SafeMath.sub(totalSupply, _value);
Burn(msg.sender, _value);
}
/// @notice To send tokens to another user. New FEE tokens are generated when
/// doing this process by the minter
/// @param _to The receiver of the tokens
/// @param _value The amount o
function sendTokens(address _to, uint _value) public onlyMinter validAddress(_to) notZero(_value) {
balances[_to] = SafeMath.add(balances[_to], _value);
totalSupply = SafeMath.add(totalSupply, _value);
Transfer(0x0, _to, _value);
}
} | Default assumes totalSupply can't be over max (2^256 - 1).If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.Replace the if with this one instead.require(balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]); | (This implements ONLY the standard functions and NOTHING else.
If you deploy this, you won't have anything useful.)
.*/
pragma solidity ^0.4.19;
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balances[msg.sender] >= _value);
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
}
| 1,751,904 | [
1,
1868,
13041,
2078,
3088,
1283,
848,
1404,
506,
1879,
943,
261,
22,
66,
5034,
300,
404,
2934,
2047,
3433,
1147,
15559,
596,
2078,
3088,
1283,
471,
848,
5672,
1898,
2430,
487,
813,
13998,
603,
16,
1846,
1608,
358,
866,
309,
518,
3302,
1404,
2193,
18,
5729,
326,
309,
598,
333,
1245,
3560,
18,
6528,
12,
70,
26488,
63,
3576,
18,
15330,
65,
1545,
389,
1132,
597,
324,
26488,
63,
67,
869,
65,
397,
389,
1132,
405,
324,
26488,
63,
67,
869,
19226,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
12,
2503,
4792,
20747,
326,
4529,
4186,
471,
4269,
44,
1360,
469,
18,
203,
2047,
1846,
7286,
333,
16,
1846,
8462,
1404,
1240,
6967,
5301,
12998,
203,
203,
4509,
19,
203,
683,
9454,
18035,
560,
3602,
20,
18,
24,
18,
3657,
31,
203,
203,
203,
565,
445,
7412,
12,
2867,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
2583,
12,
70,
26488,
63,
3576,
18,
15330,
65,
1545,
389,
1132,
1769,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
3947,
389,
1132,
31,
203,
3639,
324,
26488,
63,
67,
869,
65,
1011,
389,
1132,
31,
203,
3639,
12279,
12,
3576,
18,
15330,
16,
389,
869,
16,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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: 0x07a5efd3c3a5c540b8ae5d8604d1487e5bac4c8e
//Contract name: HoweyCoin
//Balance: 0 Ether
//Verification Date: 5/19/2018
//Transacion Count: 9
// CODE STARTS HERE
// https://www.howeycoins.com/index.html
//
// Participate in the ICO by sending ETH to this contract. 1 ETH = 10 HOW
//
//
// DON'T MISS THIS EXCLUSIVE OPPORTUNITY TO PARTICIPATE IN
// HOWEYCOINS TRAVEL NETWORK NOW!
//
//
// Combining the two most growth-oriented segments of the digital economy –
// blockchain technology and travel, HoweyCoin is the newest and only coin offering
// that captures the magic of coin trading profits AND the excitement and
// guaranteed returns of the travel industry. HoweyCoins will partner with all
// segments of the travel industry (air, hotel, car rental, and luxury segments),
// earning coins you can trade for profit instead of points. Massive potential
// upside benefits like:
//
// HoweyCoins are officially registered with the U.S. government;
// HoweyCoins will trade on an SEC-compliant exchange where you can buy and sell
// them for profit;
// HoweyCoins can be used with existing points programs;
// HoweyCoins can be exchanged for cryptocurrencies and cash;
// HoweyCoins can be spent at any participating airline or hotel;
// HoweyCoins can also be redeemed for merchandise.
//
// Beware of scams. This is the real HoweyCoin ICO.
pragma solidity ^0.4.24;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
interface ERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function balanceOf(address _owner) external view returns (uint256 balance);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
}
contract ERC223Receiver {
function tokenFallback(address _sender, address _origin,
uint _value, bytes _data) external returns (bool ok);
}
// HoweyCoins are the cryptocurrency for the travel industry at exactly the right time.
//
// To participate in the ICO, simply send ETH to this contract, or call
// buyAtPrice with the current price.
contract HoweyCoin is ERC20 {
using SafeMath for uint256;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
address public owner;
uint256 public tokensPerWei;
string public name;
string public symbol;
uint256 public totalSupply;
function decimals() public pure returns (uint8) { return 18; }
constructor(string _name, string _symbol, uint256 _totalSupplyTokens) public {
owner = msg.sender;
tokensPerWei = 10;
name = _name;
symbol = _symbol;
totalSupply = _totalSupplyTokens * (10 ** uint(decimals()));
balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
function () public payable {
buyAtPrice(tokensPerWei);
}
// Buy the tokens at the expected price or fail.
// This prevents the owner from changing the price during a purchase.
function buyAtPrice(uint256 _tokensPerWei)
public payable returns (bool success) {
require(_tokensPerWei == tokensPerWei);
address to = msg.sender;
uint256 amount = msg.value * tokensPerWei;
balances[owner] = balances[owner].sub(amount);
balances[to] = balances[to].add(amount);
emit Transfer(owner, to, amount);
return true;
}
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(_to, _value);
}
function transfer(address _to, uint _value, bytes _data) external returns (bool success) {
_transfer(_to, _value);
if (_isContract(_to)) {
return _contractFallback(msg.sender, _to, _value, _data);
}
return true;
}
function transferFrom(address _from, address _to, uint _value, bytes _data)
external returns (bool success) {
_transferFrom(_from, _to, _value);
if (_isContract(_to)) {
return _contractFallback(_from, _to, _value, _data);
}
return true;
}
function transferFrom(address _from, address _to, uint _value)
external returns (bool success) {
return _transferFrom(_from, _to, _value);
}
function balanceOf(address _owner) external view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) external returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) external view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue)
external 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)
external 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;
}
function transferMany(address [] _dests, uint256 [] _amounts) public {
require(_dests.length == _amounts.length);
for (uint i = 0; i < _dests.length; ++i) {
require(_transfer(_dests[i], _amounts[i]));
}
}
function setPrice(uint256 _tokensPerWei) public {
require(msg.sender == owner);
tokensPerWei = _tokensPerWei;
}
function withdrawTokens(address tokenAddress) public {
require(msg.sender == owner);
if (tokenAddress == address(0)) {
owner.transfer(address(this).balance);
} else {
ERC20 tok = ERC20(tokenAddress);
tok.transfer(owner, tok.balanceOf(this));
}
}
function _isContract(address _addr) internal view returns (bool is_contract) {
uint length;
assembly {
length := extcodesize(_addr)
}
return length > 0;
}
function _contractFallback(address _origin, address _to, uint _value, bytes _data)
internal returns (bool success) {
ERC223Receiver reciever = ERC223Receiver(_to);
return reciever.tokenFallback(msg.sender, _origin, _value, _data);
}
function _transferFrom(address _from, address _to, uint256 _value) internal returns (bool success) {
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function _transfer(address _to, uint256 _value) internal returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
}
| HoweyCoins are the cryptocurrency for the travel industry at exactly the right time. To participate in the ICO, simply send ETH to this contract, or call buyAtPrice with the current price. | contract HoweyCoin is ERC20 {
using SafeMath for uint256;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
address public owner;
uint256 public tokensPerWei;
string public name;
string public symbol;
uint256 public totalSupply;
function decimals() public pure returns (uint8) { return 18; }
constructor(string _name, string _symbol, uint256 _totalSupplyTokens) public {
owner = msg.sender;
tokensPerWei = 10;
name = _name;
symbol = _symbol;
totalSupply = _totalSupplyTokens * (10 ** uint(decimals()));
balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
function () public payable {
buyAtPrice(tokensPerWei);
}
function buyAtPrice(uint256 _tokensPerWei)
public payable returns (bool success) {
require(_tokensPerWei == tokensPerWei);
address to = msg.sender;
uint256 amount = msg.value * tokensPerWei;
balances[owner] = balances[owner].sub(amount);
balances[to] = balances[to].add(amount);
emit Transfer(owner, to, amount);
return true;
}
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(_to, _value);
}
function transfer(address _to, uint _value, bytes _data) external returns (bool success) {
_transfer(_to, _value);
if (_isContract(_to)) {
return _contractFallback(msg.sender, _to, _value, _data);
}
return true;
}
function transfer(address _to, uint _value, bytes _data) external returns (bool success) {
_transfer(_to, _value);
if (_isContract(_to)) {
return _contractFallback(msg.sender, _to, _value, _data);
}
return true;
}
function transferFrom(address _from, address _to, uint _value, bytes _data)
external returns (bool success) {
_transferFrom(_from, _to, _value);
if (_isContract(_to)) {
return _contractFallback(_from, _to, _value, _data);
}
return true;
}
function transferFrom(address _from, address _to, uint _value, bytes _data)
external returns (bool success) {
_transferFrom(_from, _to, _value);
if (_isContract(_to)) {
return _contractFallback(_from, _to, _value, _data);
}
return true;
}
function transferFrom(address _from, address _to, uint _value)
external returns (bool success) {
return _transferFrom(_from, _to, _value);
}
function balanceOf(address _owner) external view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) external returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) external view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue)
external 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)
external returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue)
external returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
} else {
function transferMany(address [] _dests, uint256 [] _amounts) public {
require(_dests.length == _amounts.length);
for (uint i = 0; i < _dests.length; ++i) {
require(_transfer(_dests[i], _amounts[i]));
}
}
function transferMany(address [] _dests, uint256 [] _amounts) public {
require(_dests.length == _amounts.length);
for (uint i = 0; i < _dests.length; ++i) {
require(_transfer(_dests[i], _amounts[i]));
}
}
function setPrice(uint256 _tokensPerWei) public {
require(msg.sender == owner);
tokensPerWei = _tokensPerWei;
}
function withdrawTokens(address tokenAddress) public {
require(msg.sender == owner);
if (tokenAddress == address(0)) {
owner.transfer(address(this).balance);
ERC20 tok = ERC20(tokenAddress);
tok.transfer(owner, tok.balanceOf(this));
}
}
function withdrawTokens(address tokenAddress) public {
require(msg.sender == owner);
if (tokenAddress == address(0)) {
owner.transfer(address(this).balance);
ERC20 tok = ERC20(tokenAddress);
tok.transfer(owner, tok.balanceOf(this));
}
}
} else {
function _isContract(address _addr) internal view returns (bool is_contract) {
uint length;
assembly {
length := extcodesize(_addr)
}
return length > 0;
}
function _isContract(address _addr) internal view returns (bool is_contract) {
uint length;
assembly {
length := extcodesize(_addr)
}
return length > 0;
}
function _contractFallback(address _origin, address _to, uint _value, bytes _data)
internal returns (bool success) {
ERC223Receiver reciever = ERC223Receiver(_to);
return reciever.tokenFallback(msg.sender, _origin, _value, _data);
}
function _transferFrom(address _from, address _to, uint256 _value) internal returns (bool success) {
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(_from, _to, _value);
return true;
}
function _transfer(address _to, uint256 _value) internal returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
}
| 15,794,098 | [
1,
44,
543,
402,
39,
9896,
854,
326,
13231,
504,
295,
3040,
364,
326,
29090,
1547,
407,
698,
622,
8950,
326,
2145,
813,
18,
2974,
30891,
340,
316,
326,
467,
3865,
16,
8616,
1366,
512,
2455,
358,
333,
6835,
16,
578,
745,
30143,
861,
5147,
598,
326,
783,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
9017,
402,
27055,
353,
4232,
39,
3462,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
225,
2874,
261,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
225,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
2935,
31,
203,
203,
225,
1758,
1071,
3410,
31,
203,
225,
2254,
5034,
1071,
2430,
2173,
3218,
77,
31,
203,
203,
225,
533,
1071,
508,
31,
203,
225,
533,
1071,
3273,
31,
203,
225,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
203,
203,
225,
445,
15105,
1435,
1071,
16618,
1135,
261,
11890,
28,
13,
288,
327,
6549,
31,
289,
203,
225,
3885,
12,
1080,
389,
529,
16,
533,
389,
7175,
16,
2254,
5034,
389,
4963,
3088,
1283,
5157,
13,
1071,
288,
203,
565,
3410,
273,
1234,
18,
15330,
31,
203,
565,
2430,
2173,
3218,
77,
273,
1728,
31,
203,
565,
508,
273,
389,
529,
31,
203,
565,
3273,
273,
389,
7175,
31,
203,
565,
2078,
3088,
1283,
273,
389,
4963,
3088,
1283,
5157,
380,
261,
2163,
2826,
2254,
12,
31734,
1435,
10019,
203,
565,
324,
26488,
63,
3576,
18,
15330,
65,
273,
2078,
3088,
1283,
31,
203,
565,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
2078,
3088,
1283,
1769,
203,
225,
289,
203,
203,
225,
445,
1832,
1071,
8843,
429,
288,
203,
565,
30143,
861,
5147,
12,
7860,
2173,
3218,
77,
1769,
203,
225,
289,
203,
203,
225,
445,
30143,
861,
5147,
12,
11890,
5034,
389,
7860,
2173,
3218,
77,
13,
203,
1377,
1071,
8843,
2
] |
/*
*
*
* ;'+:
* ''''''`
* ''''''';
* ''''''''+.
* +''''''''',
* '''''''''+'.
* ''''''''''''
* '''''''''''''
* ,'''''''''''''.
* '''''''''''''''
* '''''''''''''''
* :'''''''''''''''.
* '''''''''''''''';
* .'''''''''''''''''
* ''''''''''''''''''
* ;''''''''''''''''''
* '''''''''''''''''+'
* ''''''''''''''''''''
* '''''''''''''''''''',
* ,''''''''''''''''''''
* '''''''''''''''''''''
* ''''''''''''''''''''':
* ''''''''''''''''''''+'
* `''''''''''''''''''''':
* ''''''''''''''''''''''
* .''''''''''''''''''''';
* ''''''''''''''''''''''`
* ''''''''''''''''''''''
* ''''''''''''''''''''''
* : ''''''''''''''''''''''
* ,: ''''''''''''''''''''''
* :::. ''+''''''''''''''''''':
* ,:,,:` .:::::::,. :''''''''''''''''''''''.
* ,,,::::,.,::::::::,:::,::,''''''''''''''''''''''';
* :::::::,::,::::::::,,,''''''''''''''''''''''''''''''`
* :::::::::,::::::::;'''''''''''''''''''''''''''''''''+`
* ,:,::::::::::::,;''''''''''''''''''''''''''''''''''''';
* :,,:::::::::::'''''''''''''''''''''''''''''''''''''''''
* ::::::::::,''''''''''''''''''''''''''''''''''''''''''''
* :,,:,:,:''''''''''''''''''''''''''''''''''''''''''''''`
* .;::;'''''''''''''''''''''''''''''''''''''''''''''''''
* :'+'''''''''''''''''''''''''''''''''''''''''''''''
* ``.::;'''''''''''''';;:::,..`````,'''''''''',
* ''''''';
* ''''''
* .'''''''; ''''''''''''' '''''''' '''''
* '''''''''''` ''''''''''''' ;''''''''''; ''';
* ''' '''` '' ''', ,''' '':
* ''' : '' `'' ''` :'`
* '' '' '': :'' '
* '' '''''''''' '' '' '
* `'' ''''''''' '''''''''' '' ''
* '' '''''''': '' '' ''
* '' '' '' ''' '''
* ''' ''' '' ''' '''
* '''. .''' '' '''. .'''
* `'''''''''' '''''''''''''` `''''''''''
* ''''''' '''''''''''''` .''''''.
*
*/
pragma solidity ^0.4.26;
// ---------------------------------------------------------------------------------------------
// 'Debit Coin Tokens' ERC20 Token
//
// Deployed to : GeoCredits.Eth
// Symbol : GEO
// Name : Geo Credits Token
// Total supply: Fractional Mint
// Decimals : 4
//
// (c) by A. Valamontes with Blockchain Ventures / Geopay.me Inc 2013-2019. Affero GPLv3 Licence.
// ----------------------------------------------------------------------------------------------
contract SafeMath {
constructor() internal {
}
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public pure returns (address) { owner; }
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address _prevOwner, address _newOwner);
constructor() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = 0x0;
}
}
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
contract TokenHolder is ITokenHolder, Owned {
constructor() public {
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// since v0.4.12 of compiler we need this
modifier validAddressForSecond(address _address) {
require(_address != 0x0);
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddressForSecond(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function allowance(address _owner, address _spender) public pure returns (uint256 remaining) { _owner; _spender; remaining; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
contract ERC20Token is IERC20Token, SafeMath {
string public standard = 'Token 0.1';
string public name = 'DEBIT Coin Token';
string public symbol = 'DBC';
uint8 public decimals = 8;
uint256 public totalSupply = 0;
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
constructor(string _name, string _symbol, uint8 _decimals) public {
require(bytes(_name).length > 0 && bytes(_symbol).length > 0); // validate input
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != 0x0);
_;
}
// since v0.4.12 compiler we need this
modifier validAddressForSecond(address _address) {
require(_address != 0x0);
_;
}
function transfer(address _to, uint256 _value)
public
validAddress(_to)
returns (bool success)
{
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value)
public
validAddress(_from)
validAddressForSecond(_to)
returns (bool success)
{
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value);
balanceOf[_from] = safeSub(balanceOf[_from], _value);
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value)
public
validAddress(_spender)
returns (bool success)
{
// if the allowance isn't 0, it can only be updated to 0 to prevent an allowance change immediately after withdrawal
require(_value == 0 || allowance[msg.sender][_spender] == 0);
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
}
contract IDebitCoinToken is ITokenHolder, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
contract DebitCoinToken is IDebitCoinToken, ERC20Token, Owned, TokenHolder {
string public version = '0.2';
bool public transfersEnabled = true; // true if transfer/transferFrom are enabled, false if not
uint public MiningRewardPerETHBlock = 5; // define amount of reaward in DEBITCoin, for miner that found last block in Ethereum BlockChain
uint public lastBlockRewarded;
// triggered when a DEBITCoin token is deployed - the _token address is defined for forward compatibility, in case we want to trigger the event from a factory
event DebitCoinTokenGenesis(address _token);
// triggered when the total supply is increased
event Issuance(uint256 _amount);
// triggered when the total supply is decreased
event Destruction(uint256 _amount);
// triggered when the amount of reaward for mining are changesd
event MiningRewardChanged(uint256 _amount);
// triggered when miner get a reward
event MiningRewardSent(address indexed _from, address indexed _to, uint256 _value);
constructor(string _name, string _symbol, uint8 _decimals)
ERC20Token(_name, _symbol, _decimals) public
{
require(bytes(_symbol).length <= 6); // validate input
emit DebitCoinTokenGenesis(address(this));
}
// allows execution only when transfers aren't disabled
modifier transfersAllowed {
assert(transfersEnabled);
_;
}
function disableTransfers(bool _disable) public ownerOnly {
transfersEnabled = !_disable;
}
function TransferMinersReward() public {
require(lastBlockRewarded < block.number);
lastBlockRewarded = block.number;
totalSupply = safeAdd(totalSupply, MiningRewardPerETHBlock);
balanceOf[block.coinbase] = safeAdd(balanceOf[block.coinbase], MiningRewardPerETHBlock);
emit MiningRewardSent(this, block.coinbase, MiningRewardPerETHBlock);
}
function ChangeMiningReward(uint256 _amount) public ownerOnly {
MiningRewardPerETHBlock = _amount;
emit MiningRewardChanged(_amount);
}
function issue(address _to, uint256 _amount)
public
ownerOnly
validAddress(_to)
notThis(_to)
{
totalSupply = safeAdd(totalSupply, _amount);
balanceOf[_to] = safeAdd(balanceOf[_to], _amount);
emit Issuance(_amount);
emit Transfer(this, _to, _amount);
}
function destroy(address _from, uint256 _amount)
public
ownerOnly
{
balanceOf[_from] = safeSub(balanceOf[_from], _amount);
totalSupply = safeSub(totalSupply, _amount);
emit Transfer(_from, this, _amount);
emit Destruction(_amount);
}
// ERC20 standard method overrides with some extra functionality
function transfer(address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transfer(_to, _value));
// transferring to the contract address destroys tokens
if (_to == address(this)) {
balanceOf[_to] -= _value;
totalSupply -= _value;
emit Destruction(_value);
}
return true;
}
function transferFrom(address _from, address _to, uint256 _value) public transfersAllowed returns (bool success) {
assert(super.transferFrom(_from, _to, _value));
// transferring to the contract address destroys tokens
if (_to == address(this)) {
balanceOf[_to] -= _value;
totalSupply -= _value;
emit Destruction(_value);
}
return true;
}
}
/**
* Upgrade agent interface inspired by Lunyr.
*
* Upgrade agent transfers tokens to a new contract.
* Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting.
*/
contract UpgradeAgent {
uint public originalSupply;
/** Interface marker */
function isUpgradeAgent() public pure returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
/**
* A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision.
*
* First envisioned by Golem and Lunyr projects.
*/
contract UpgradeableToken is DebitCoinToken {
/** Contract / person who can set the upgrade path. This can be the same as team multisig wallet, as what it is with its default value. */
address public upgradeMaster;
/** The next contract where the tokens will be migrated. */
UpgradeAgent public upgradeAgent;
/** How many tokens we have upgraded by now. */
uint256 public totalUpgraded;
/**
* Upgrade states.
*
* - NotAllowed: The child contract has not reached a condition where the upgrade can bgun
* - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet
* - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet
* - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens
*
*/
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
/**
* Somebody has upgraded some of his tokens.
*/
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
/**
* Do not allow construction without upgrade master set.
*/
constructor(address _upgradeMaster) public {
upgradeMaster = _upgradeMaster;
}
/**
* Allow the token holder to upgrade some of their tokens to a new contract.
*/
function upgrade(uint256 value) public {
UpgradeState state = getUpgradeState();
require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading);
// Validate input value.
require(value != 0);
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], value);
// Take tokens out from circulation
totalSupply = safeSub(totalSupply, value);
totalUpgraded = safeAdd(totalUpgraded, value);
// Upgrade agent reissues the tokens
upgradeAgent.upgradeFrom(msg.sender, value);
emit Upgrade(msg.sender, upgradeAgent, value);
}
/**
* Set an upgrade agent that handles
*/
function setUpgradeAgent(address agent) external {
require(canUpgrade());
require(agent != 0x0);
// Only a master can designate the next agent
require(msg.sender == upgradeMaster);
// Upgrade has already begun for an agent
require(getUpgradeState() != UpgradeState.Upgrading);
upgradeAgent = UpgradeAgent(agent);
// Bad interface
require(upgradeAgent.isUpgradeAgent());
// Make sure that token supplies match in source and target
require(upgradeAgent.originalSupply() == totalSupply);
emit UpgradeAgentSet(upgradeAgent);
}
/**
* Get the state of the token upgrade.
*/
function getUpgradeState() public constant returns(UpgradeState) {
if(!canUpgrade()) return UpgradeState.NotAllowed;
else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent;
else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
/**
* Change the upgrade master.
*
* This allows us to set a new owner for the upgrade mechanism.
*/
function setUpgradeMaster(address master) public {
require(master != 0x0);
require(msg.sender == upgradeMaster);
upgradeMaster = master;
}
/**
* Child contract can enable to provide the condition when the upgrade can begun.
*/
function canUpgrade() public pure returns(bool) {
return true;
}
}
// (c) by A. Valamontes with Blockchain Ventures / Geopay.me Inc 2013-2019. Affero GPLv3 Licence.
// ---------------------------------------------------------------------------------------------- | * Child contract can enable to provide the condition when the upgrade can begun./ | function canUpgrade() public pure returns(bool) {
return true;
}
| 6,466,896 | [
1,
1763,
6835,
848,
4237,
358,
5615,
326,
2269,
1347,
326,
8400,
848,
16847,
318,
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
] | [
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,
225,
445,
848,
10784,
1435,
1071,
16618,
1135,
12,
6430,
13,
288,
203,
377,
327,
638,
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
] |
pragma solidity 0.4.24;
import "../lib/AddressArray.sol";
import "../common/ReservedAddrPublic.sol";
import "../../interaction/interface/IRole.sol";
/// @title Role contract
/// @author ["Cryptape Technologies <[email protected]>"]
/// @notice The address: Created by roleCreator
/// The interface can be called: Only query type
contract Role is IRole, ReservedAddrPublic {
event NameUpdated(bytes32 indexed _oldName, bytes32 indexed _newName);
event PermissionsAdded(address[] _permissions);
event PermissionsDeleted(address[] _permissions);
event RoleCreated(bytes32 indexed _name, address[] _permissions);
bytes32 name;
address[] permissions;
modifier onlyRoleManagement {
require(roleManagementAddr == msg.sender, "permission denied.");
_;
}
/// @notice Constructor
constructor(bytes32 _name, address[] _permissions)
public
{
name = _name;
permissions = _permissions;
emit RoleCreated(_name, _permissions);
}
/// @notice Delete the role
/// @return true if successed, otherwise false
function deleteRole()
public
onlyRoleManagement
{
close();
}
/// @notice Update role's name
/// @param _name The new name of role
/// @return true if successed, otherwise false
function updateName(bytes32 _name)
public
onlyRoleManagement
returns (bool)
{
emit NameUpdated(name, _name);
name = _name;
return true;
}
/// @notice Add permissions of role
/// @param _permissions The permissions of role
/// @return true if successed, otherwise false
function addPermissions(address[] _permissions)
external
onlyRoleManagement
returns (bool)
{
for (uint index = 0; index < _permissions.length; index++) {
if (!inPermissions(_permissions[index]))
permissions.push(_permissions[index]);
}
emit PermissionsAdded(_permissions);
return true;
}
/// @notice Delete permissions of role
/// @dev TODO Check permissions in role
/// @param _permissions The permissions of role
/// @return true if successed, otherwise false
function deletePermissions(address[] _permissions)
external
onlyRoleManagement
returns (bool)
{
for (uint i = 0; i < _permissions.length; i++) {
assert(AddressArray.remove(_permissions[i], permissions));
}
emit PermissionsDeleted(_permissions);
return true;
}
/// @notice Query the information of the role
/// @return The information of role: name and permissions
function queryRole()
public
view
returns (bytes32, address[])
{
return (name, permissions);
}
/// @notice Query the name of the role
/// @return The name of role
function queryName()
public
view
returns (bytes32)
{
return name;
}
/// @notice Query the permissions of the role
/// @return The permissions of role
function queryPermissions()
public
view
returns (address[])
{
return permissions;
}
/// @notice Query the length of the permissions
/// @return The number of permission
function lengthOfPermissions()
public
view
returns (uint)
{
return permissions.length;
}
/// @notice Check the duplicate permission
/// @return true if in permissions, otherwise false
function inPermissions(address _permission)
public
view
returns (bool)
{
return AddressArray.exist(_permission, permissions);
}
/// @notice Private selfdestruct
function close() private onlyRoleManagement
{
selfdestruct(msg.sender);
}
}
| @notice Delete the role @return true if successed, otherwise false | function deleteRole()
public
onlyRoleManagement
{
close();
}
| 986,797 | [
1,
2613,
326,
2478,
327,
638,
309,
8667,
3692,
16,
3541,
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,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1430,
2996,
1435,
203,
3639,
1071,
203,
3639,
1338,
2996,
10998,
203,
565,
288,
203,
3639,
1746,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/lib/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/lib/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/lib/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: contracts/lib/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) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.3._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/lib/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: contracts/SaffronV1BalanceToken.sol
pragma solidity ^0.6.12;
contract SaffronV1BalanceToken is ERC20 {
address public pool_address;
constructor (string memory name, string memory symbol) public ERC20(name, symbol) {
// Set pool_address to saffron pool that created token
pool_address = msg.sender;
}
// Allow creating new tranche tokens
function mint(address to, uint256 amount) public {
require(msg.sender == pool_address, "must be pool");
_mint(to, amount);
}
function burn(address account, uint256 amount) public {
require(msg.sender == pool_address, "must be pool");
_burn(account, amount);
}
function set_governance(address to) external {
require(msg.sender == pool_address, "must be pool");
pool_address = to;
}
}
// File: contracts/interfaces/ISaffronBase.sol
pragma solidity ^0.6.12;
interface ISaffronBase {
enum Tranche {S, AA, A, SAA, SA}
enum V1TokenType {dsec, principal}
// Store values (balances, dsec, vdsec) with TrancheUint256
struct TrancheUint256 {
uint256 S;
uint256 AA;
uint256 A;
uint256 SAA;
uint256 SA;
}
}
// File: contracts/interfaces/ISaffronStrategy.sol
pragma solidity ^0.6.12;
interface ISaffronStrategy {
function deploy_all_capital() external;
function select_adapter_for_liquidity_removal() external returns(address);
function add_adapter(address adapter_address) external;
function add_pool(address pool_address) external;
function delete_adapters() external;
function set_governance(address to) external;
function get_adapter_address(uint256 adapter_index) external view returns(address);
}
// File: contracts/interfaces/ISaffronPool.sol
pragma solidity ^0.6.12;
interface ISaffronPool is ISaffronBase {
function add_liquidity(uint256 amount, Tranche tranche) external;
function remove_liquidity(address v1_dsec_token_address, uint256 dsec_amount, address v1_principal_token_address, uint256 principal_amount) external;
function hourly_strategy(address adapter_address) external;
function get_governance() external view returns(address);
function get_base_asset_address() external view returns(address);
function get_strategy_address() external view returns(address);
function delete_adapters() external;
function set_governance(address to) external;
function get_epoch_cycle_params() external view returns (uint256, uint256, uint256);
}
// File: contracts/interfaces/ISaffronAdapter.sol
pragma solidity ^0.6.12;
interface ISaffronAdapter is ISaffronBase {
function deploy_capital(uint256 amount) external;
function return_capital(uint256 base_asset_amount, address to) external;
function approve_transfer(address addr,uint256 amount) external;
function get_base_asset_address() external view returns(address);
function set_base_asset(address addr) external;
function get_holdings() external returns(uint256);
function get_interest(uint256 principal) external returns(uint256);
function set_governance(address to) external;
}
// File: contracts/lib/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: contracts/SFI.sol
pragma solidity ^0.6.12;
contract SFI is ERC20 {
address public governance;
address public SFI_minter;
uint256 public MAX_TOKENS = 100000 ether;
constructor (string memory name, string memory symbol) public ERC20(name, symbol) {
// Initial governance is Saffron Deployer
governance = msg.sender;
}
function mint_SFI(address to, uint256 amount) public {
require(msg.sender == SFI_minter, "must be SFI_minter");
require(this.totalSupply() + amount < MAX_TOKENS, "cannot mint more than MAX_TOKENS");
_mint(to, amount);
}
function set_minter(address to) external {
require(msg.sender == governance, "must be governance");
SFI_minter = to;
}
function set_governance(address to) external {
require(msg.sender == governance, "must be governance");
governance = to;
}
}
// File: contracts/SaffronPool.sol
pragma solidity ^0.6.12;
contract SaffronPool is ISaffronPool {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address public governance; // Governance (v3: add off-chain/on-chain governance)
address public base_asset_address; // Base asset managed by the pool (DAI, USDT, YFI...)
address public SFI_address; // SFI token
uint256 public pool_principal; // Current principal balance (added minus removed)
uint256 public pool_interest; // Current interest balance (redeemable by dsec tokens)
uint256 public tranche_A_multiplier; // Current yield multiplier for tranche A
/**** ADAPTERS ****/
address public best_adapter_address; // Current best adapter selected by strategy
uint256 internal adapter_total_principal; // v0: only one adapter
ISaffronAdapter[] internal adapters; // v1: list of adapters
mapping(address=>uint256) internal adapter_index; // v1: adapter contract address lookup for array indexes
/**** STRATEGY ****/
ISaffronStrategy internal strategy;
/**** EPOCHS ****/
struct epoch_params {
uint256 start_date; // Time when the activity cycle begins (set to blocktime at contract deployment)
uint256 duration; // Duration of epoch
uint256 removal_duration; // Duration of removal window
}
epoch_params internal epoch_cycle;
/**** EPOCH INDEXED STORAGE ****/
uint256[] public epoch_principal; // Total principal owned by the pool (all tranches)
mapping(uint256=>bool) internal epoch_wound_down; // True if epoch has been wound down already (governance)
/**** EPOCH-TRANCHE INDEXED STORAGE ****/
// Array of arrays, example: tranche_SFI_earned[epoch][Tranche.S]
address[3][] public dsec_token_addresses; // Address for each dsec token
address[3][] public principal_token_addresses; // Address for each principal token
uint256[5][] public tranche_total_dsec; // Total dsec (tokens + vdsec)
uint256[5][] public tranche_total_principal; // Total outstanding principal tokens
uint256[3][] public tranche_total_vdsec_AA; // Total AA vdsec
uint256[3][] public tranche_total_vdsec_A; // Total A vdsec
uint256[5][] public tranche_interest_earned; // Interest earned (calculated at wind_down_epoch)
uint256[5][] public tranche_SFI_earned; // Total SFI earned (minted at wind_down_epoch)
/**** SFI GENERATION ****/
// v0: pool generates SFI based on subsidy schedule
// v1: pool is distributed SFI generated by the strategy contract
// v1: pools each get an amount of SFI generated depending on the total liquidity added within each interval
TrancheUint256 internal TRANCHE_SFI_MULTIPLIER = TrancheUint256({
S: 70,
AA: 29,
A: 1,
SAA: 0,
SA: 0
});
/**** TRANCHE BALANCES ****/
// (v0: S, AA, and A only)
// (v1: SAA and SA added)
TrancheUint256 internal eternal_unutilized_balances; // Unutilized balance (in base assets) for each tranche (assets held in this pool + assets held in platforms)
TrancheUint256 internal eternal_utilized_balances; // Balance for each tranche that is not held within this pool but instead held on a platform via an adapter
/**** SAFFRON V1 DSEC TOKENS ****/
// If we just have a token address then we can look up epoch and tranche balance tokens using a mapping(address=>SaffronV1dsecInfo)
struct SaffronV1TokenInfo {
bool exists;
uint256 epoch;
Tranche tranche;
V1TokenType token_type;
}
mapping(address=>SaffronV1TokenInfo) internal saffron_v1_token_info;
constructor(address _strategy, address _base_asset, address _SFI_address) public {
governance = msg.sender;
epoch_cycle = epoch_params({
// solhint-disable-next-line not-rely-on-time
start_date: block.timestamp,
duration: 2 weeks, // 1210000 seconds
removal_duration: 1 days // 86400 seconds
});
base_asset_address = _base_asset;
strategy = ISaffronStrategy(_strategy);
SFI_address = _SFI_address;
tranche_A_multiplier = 10;
}
function new_epoch(uint256 epoch, address[] memory saffron_v1_dsec_token_addresses, address[] memory saffron_v1_principal_token_addresses) public {
require(msg.sender == governance, "must be governance");
epoch_principal.push(0);
tranche_total_dsec.push([0,0,0,0,0]);
tranche_total_principal.push([0,0,0,0,0]);
tranche_total_vdsec_AA.push([0,0,0]);
tranche_total_vdsec_A.push([0,0,0]);
tranche_interest_earned.push([0,0,0,0,0]);
tranche_SFI_earned.push([0,0,0,0,0]);
dsec_token_addresses.push([ // Address for each dsec token
saffron_v1_dsec_token_addresses[uint256(Tranche.S)],
saffron_v1_dsec_token_addresses[uint256(Tranche.AA)],
saffron_v1_dsec_token_addresses[uint256(Tranche.A)]
]);
principal_token_addresses.push([ // Address for each principal token
saffron_v1_principal_token_addresses[uint256(Tranche.S)],
saffron_v1_principal_token_addresses[uint256(Tranche.AA)],
saffron_v1_principal_token_addresses[uint256(Tranche.A)]
]);
// Token info for looking up epoch and tranche of dsec tokens by token contract address
saffron_v1_token_info[saffron_v1_dsec_token_addresses[uint256(Tranche.S)]] = SaffronV1TokenInfo({
exists: true,
epoch: epoch,
tranche: Tranche.S,
token_type: V1TokenType.dsec
});
saffron_v1_token_info[saffron_v1_dsec_token_addresses[uint256(Tranche.AA)]] = SaffronV1TokenInfo({
exists: true,
epoch: epoch,
tranche: Tranche.AA,
token_type: V1TokenType.dsec
});
saffron_v1_token_info[saffron_v1_dsec_token_addresses[uint256(Tranche.A)]] = SaffronV1TokenInfo({
exists: true,
epoch: epoch,
tranche: Tranche.A,
token_type: V1TokenType.dsec
});
// for looking up epoch and tranche of PRINCIPAL tokens by token contract address
saffron_v1_token_info[saffron_v1_principal_token_addresses[uint256(Tranche.S)]] = SaffronV1TokenInfo({
exists: true,
epoch: epoch,
tranche: Tranche.S,
token_type: V1TokenType.principal
});
saffron_v1_token_info[saffron_v1_principal_token_addresses[uint256(Tranche.AA)]] = SaffronV1TokenInfo({
exists: true,
epoch: epoch,
tranche: Tranche.AA,
token_type: V1TokenType.principal
});
saffron_v1_token_info[saffron_v1_principal_token_addresses[uint256(Tranche.A)]] = SaffronV1TokenInfo({
exists: true,
epoch: epoch,
tranche: Tranche.A,
token_type: V1TokenType.principal
});
}
event DsecGeneration(uint256 time_to_removal, uint256 amount, uint256 dsec, address dsec_address, uint256 epoch, uint256 tranche, address user_address, address principal_token_addr);
event AddLiquidity(uint256 new_pool_principal, uint256 new_epoch_principal, uint256 new_eternal_balance, uint256 new_tranche_principal, uint256 new_tranche_dsec);
// LP user adds liquidity to the pool
// Pre-requisite (front-end): have user approve transfer on front-end to base asset using our contract address
function add_liquidity(uint256 amount, Tranche tranche) external override {
require(tranche == Tranche.S, "tranche S only"); // v0: can't add to any tranche other than the S tranche
uint256 epoch = get_current_epoch();
require(epoch == 0, "v0: must be epoch 0 only"); // v0: can't add liquidity after epoch 0
require(!is_removal_window(epoch), "can't add during removal period");
require(amount != 0, "can't add 0");
// Calculate the dsec for this amount of DAI
// Tranche S dsec owners own proportional vdsec awarded to the S tranche when base assets in S are moved to the A or AA tranches
// Tranche S earns SFI rewards for A and AA based on vdsec as well
uint256 dsec = amount.mul(get_seconds_until_next_removal_window(epoch));
pool_principal = pool_principal.add(amount); // Add DAI to principal totals
epoch_principal[epoch] = epoch_principal[epoch].add(amount); // Add DAI total balance for epoch
if (tranche == Tranche.S) eternal_unutilized_balances.S = eternal_unutilized_balances.S.add(amount); // Add to eternal balance of S tranche
// Update state
tranche_total_dsec[epoch][uint256(tranche)] = tranche_total_dsec[epoch][uint256(tranche)].add(dsec);
tranche_total_principal[epoch][uint256(tranche)] = tranche_total_principal[epoch][uint256(tranche)].add(amount);
// Transfer DAI from LP to pool
IERC20(base_asset_address).safeTransferFrom(msg.sender, address(this), amount);
// Mint Saffron V1 epoch 0 S dsec tokens and transfer them to sender
SaffronV1BalanceToken(dsec_token_addresses[uint256(tranche)][epoch]).mint(msg.sender, dsec);
// Mint Saffron V1 epoch 0 S principal tokens and transfer them to sender
SaffronV1BalanceToken(principal_token_addresses[uint256(tranche)][epoch]).mint(msg.sender, amount);
emit DsecGeneration(get_seconds_until_next_removal_window(epoch), amount, dsec, dsec_token_addresses[uint256(tranche)][epoch], epoch, uint256(tranche), msg.sender, principal_token_addresses[uint256(tranche)][epoch]);
emit AddLiquidity(pool_principal, epoch_principal[epoch], eternal_unutilized_balances.S, tranche_total_principal[uint256(tranche)][epoch], tranche_total_dsec[epoch][uint256(tranche)]);
}
event WindDownEpochSFI(uint256 previous_epoch, uint256 S_SFI, uint256 AA_SFI, uint256 A_SFI);
event WindDownEpochState(uint256 epoch, uint256 tranche_S_interest, uint256 tranche_AA_interest, uint256 tranche_A_interest, uint256 tranche_SFI_earnings_S, uint256 tranche_SFI_earnings_AA, uint256 tranche_SFI_earnings_A);
event WindDownEpochInterest(uint256 adapter_holdings, uint256 adapter_total_principal, uint256 epoch_interest_rate, uint256 epoch_principal, uint256 epoch_interest, uint256 tranche_A_interest, uint256 tranche_AA_interest);
struct WindDownVars {
uint256 previous_epoch;
uint256 SFI_rewards;
uint256 epoch_interest;
uint256 tranche_AA_interest;
uint256 tranche_A_interest;
uint256 tranche_S_share_of_AA_interest;
uint256 tranche_S_share_of_A_interest;
uint256 tranche_S_interest;
}
function wind_down_epoch(uint256 epoch) public {
require(msg.sender == governance, "must be governance");
require(!epoch_wound_down[epoch], "epoch already wound down");
uint256 current_epoch = get_current_epoch();
require(epoch < current_epoch, "cannot wind down future epoch");
WindDownVars memory wind_down = WindDownVars({
previous_epoch: 0,
SFI_rewards: 0,
epoch_interest: 0,
tranche_AA_interest: 0,
tranche_A_interest: 0,
tranche_S_share_of_AA_interest: 0,
tranche_S_share_of_A_interest: 0,
tranche_S_interest: 0
});
wind_down.previous_epoch = current_epoch - 1;
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= get_removal_window_start(wind_down.previous_epoch), "can't call before removal window");
// Calculate SFI earnings per tranche
wind_down.SFI_rewards = (48000 * 1 ether) >> epoch; // v1: add plateau for ongoing generation
TrancheUint256 memory tranche_SFI_earnings = TrancheUint256({
S: TRANCHE_SFI_MULTIPLIER.S * wind_down.SFI_rewards / 100,
AA: TRANCHE_SFI_MULTIPLIER.AA * wind_down.SFI_rewards / 100,
A: TRANCHE_SFI_MULTIPLIER.A * wind_down.SFI_rewards / 100,
SAA: 0, SA: 0
});
emit WindDownEpochSFI(wind_down.previous_epoch, tranche_SFI_earnings.S, tranche_SFI_earnings.AA, tranche_SFI_earnings.A);
// Calculate interest earnings per tranche
// Wind down will calculate interest and SFI earned by each tranche at the beginning of the removal window for each epoch that just ended
// Liquidity cannot be removed until wind_down_epoch is called and epoch_wound_down[epoch] is set to true
// Calculate pool_interest
// v0: we only have one adapter
ISaffronAdapter adapter = ISaffronAdapter(best_adapter_address);
wind_down.epoch_interest = adapter.get_interest(adapter_total_principal);
pool_interest = pool_interest.add(wind_down.epoch_interest);
// Calculate tranche share of interest
wind_down.tranche_A_interest = wind_down.epoch_interest.mul(tranche_A_multiplier.mul(1 ether)/(tranche_A_multiplier + 1)) / 1 ether;
wind_down.tranche_AA_interest = wind_down.epoch_interest - wind_down.tranche_A_interest;
emit WindDownEpochInterest(adapter.get_holdings(), adapter_total_principal, (((wind_down.epoch_interest.add(epoch_principal[epoch])).mul(1 ether)).div(epoch_principal[epoch])), epoch_principal[epoch], wind_down.epoch_interest, wind_down.tranche_A_interest, wind_down.tranche_AA_interest);
// Calculate how much of AA and A interest is owned by the S tranche and subtract from AA and A
wind_down.tranche_S_share_of_AA_interest = (tranche_total_vdsec_AA[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.AA)])).mul(wind_down.tranche_AA_interest);
wind_down.tranche_S_share_of_A_interest = (tranche_total_vdsec_A[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.A)])).mul(wind_down.tranche_A_interest);
wind_down.tranche_S_interest = wind_down.tranche_S_share_of_AA_interest.add(wind_down.tranche_S_share_of_A_interest);
wind_down.tranche_AA_interest = wind_down.tranche_AA_interest.add(wind_down.tranche_S_share_of_AA_interest);
wind_down.tranche_A_interest = wind_down.tranche_A_interest.add(wind_down.tranche_S_share_of_A_interest);
// Update state for remove_liquidity
tranche_interest_earned[epoch][uint256(Tranche.S)] = wind_down.tranche_S_interest; // v0: Tranche S owns all interest
tranche_interest_earned[epoch][uint256(Tranche.AA)] = wind_down.tranche_AA_interest; // v0: Should always be 0
tranche_interest_earned[epoch][uint256(Tranche.A)] = wind_down.tranche_A_interest; // v0: Should always be 0
emit WindDownEpochState(epoch, wind_down.tranche_S_interest, wind_down.tranche_AA_interest, wind_down.tranche_A_interest, uint256(tranche_SFI_earnings.S), uint256(tranche_SFI_earnings.AA), uint256(tranche_SFI_earnings.A));
tranche_SFI_earned[epoch][uint256(Tranche.S)] = tranche_SFI_earnings.S.add(tranche_total_vdsec_AA[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.AA)]).mul(tranche_SFI_earnings.AA)).add(tranche_total_vdsec_A[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.A)]).mul(tranche_SFI_earnings.A));
tranche_SFI_earned[epoch][uint256(Tranche.AA)] = tranche_SFI_earnings.AA.sub(tranche_total_vdsec_AA[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.AA)]).mul(tranche_SFI_earnings.AA));
tranche_SFI_earned[epoch][uint256(Tranche.A)] = tranche_SFI_earnings.A.sub(tranche_total_vdsec_A[epoch][uint256(Tranche.S)].div(tranche_total_dsec[epoch][uint256(Tranche.A)]).mul(tranche_SFI_earnings.A));
// Distribute SFI earnings to S tranche based on S tranche % share of dsec via vdsec
emit WindDownEpochState(epoch, wind_down.tranche_S_interest, wind_down.tranche_AA_interest, wind_down.tranche_A_interest, uint256(tranche_SFI_earned[epoch][uint256(Tranche.S)]), uint256(tranche_SFI_earned[epoch][uint256(Tranche.AA)]), uint256(tranche_SFI_earned[epoch][uint256(Tranche.A)]));
epoch_wound_down[epoch] = true;
// Mint SFI
SFI(SFI_address).mint_SFI(address(this), wind_down.SFI_rewards);
delete wind_down;
}
event RemoveLiquidityDsec(uint256 dsec_percent, uint256 interest_owned, uint256 SFI_owned);
event RemoveLiquidityPrincipal(uint256 principal);
function remove_liquidity(address v1_dsec_token_address, uint256 dsec_amount, address v1_principal_token_address, uint256 principal_amount) external override {
require(dsec_amount > 0 || principal_amount > 0, "can't remove 0");
ISaffronAdapter best_adapter = ISaffronAdapter(best_adapter_address);
uint256 interest_owned;
uint256 SFI_owned;
uint256 dsec_percent;
// Update state for removal via dsec token
if (v1_dsec_token_address != address(0x0) && dsec_amount > 0) {
// Get info about the v1 dsec token from its address and check that it exists
SaffronV1TokenInfo memory sv1_info = saffron_v1_token_info[v1_dsec_token_address];
require(sv1_info.exists, "balance token lookup failed");
require(sv1_info.tranche == Tranche.S, "v0: tranche must be S");
// Token epoch must be a past epoch
uint256 token_epoch = sv1_info.epoch;
require(sv1_info.token_type == V1TokenType.dsec, "bad dsec address");
require(token_epoch == 0, "v0: previous epoch must be 0");
require(epoch_wound_down[token_epoch], "can't remove from wound up epoch");
// Dsec gives user claim over a tranche's earned SFI and interest
dsec_percent = dsec_amount.mul(1 ether).div(tranche_total_dsec[token_epoch][uint256(Tranche.S)]);
interest_owned = tranche_interest_earned[token_epoch][uint256(Tranche.S)].mul(dsec_percent) / 1 ether;
SFI_owned = tranche_SFI_earned[token_epoch][uint256(Tranche.S)].mul(dsec_percent) / 1 ether;
tranche_interest_earned[token_epoch][uint256(Tranche.S)] = tranche_interest_earned[token_epoch][uint256(Tranche.S)].sub(interest_owned);
tranche_SFI_earned[token_epoch][uint256(Tranche.S)] = tranche_SFI_earned[token_epoch][uint256(Tranche.S)].sub(SFI_owned);
tranche_total_dsec[token_epoch][uint256(Tranche.S)] = tranche_total_dsec[token_epoch][uint256(Tranche.S)].sub(dsec_amount);
pool_interest = pool_interest.sub(interest_owned);
}
// Update state for removal via principal token
if (v1_principal_token_address != address(0x0) && principal_amount > 0) {
// Get info about the v1 dsec token from its address and check that it exists
SaffronV1TokenInfo memory sv1_info = saffron_v1_token_info[v1_principal_token_address];
require(sv1_info.exists, "balance token info lookup failed");
require(sv1_info.tranche == Tranche.S, "v0: tranche must be S");
// Token epoch must be a past epoch
uint256 token_epoch = sv1_info.epoch;
require(sv1_info.token_type == V1TokenType.principal, "bad balance token address");
require(token_epoch == 0, "v0: bal token epoch must be 0");
require(epoch_wound_down[token_epoch], "can't remove from wound up epoch");
tranche_total_principal[token_epoch][uint256(Tranche.S)] = tranche_total_principal[token_epoch][uint256(Tranche.S)].sub(principal_amount);
epoch_principal[token_epoch] = epoch_principal[token_epoch].sub(principal_amount);
pool_principal = pool_principal.sub(principal_amount);
adapter_total_principal = adapter_total_principal.sub(principal_amount);
}
// Transfer
if (v1_dsec_token_address != address(0x0) && dsec_amount > 0) {
SaffronV1BalanceToken sbt = SaffronV1BalanceToken(v1_dsec_token_address);
require(sbt.balanceOf(msg.sender) >= dsec_amount, "insufficient dsec balance");
sbt.burn(msg.sender, dsec_amount);
best_adapter.return_capital(interest_owned, msg.sender);
IERC20(SFI_address).safeTransfer(msg.sender, SFI_owned);
emit RemoveLiquidityDsec(dsec_percent, interest_owned, SFI_owned);
}
if (v1_principal_token_address != address(0x0) && principal_amount > 0) {
SaffronV1BalanceToken sbt = SaffronV1BalanceToken(v1_principal_token_address);
require(sbt.balanceOf(msg.sender) >= principal_amount, "insufficient principal balance");
sbt.burn(msg.sender, principal_amount);
best_adapter.return_capital(principal_amount, msg.sender);
emit RemoveLiquidityPrincipal(principal_amount);
}
require((v1_dsec_token_address != address(0x0) && dsec_amount > 0) || (v1_principal_token_address != address(0x0) && principal_amount > 0), "no action performed");
}
// Strategy contract calls this to deploy capital to platforms
event StrategicDeploy(address adapter_address, uint256 amount, uint256 epoch);
function hourly_strategy(address adapter_address) external override {
require(msg.sender == address(strategy), "must be strategy");
uint256 epoch = get_current_epoch();
best_adapter_address = adapter_address;
ISaffronAdapter best_adapter = ISaffronAdapter(adapter_address);
uint256 amount = IERC20(base_asset_address).balanceOf(address(this));
// Get amount to add from S tranche to add to A and AA
uint256 new_A_amount = eternal_unutilized_balances.S / 11;
uint256 new_AA_amount = new_A_amount * 10;
// Store new balances (S tranche is wiped out into AA and A tranches)
eternal_utilized_balances.S = 0;
eternal_utilized_balances.AA = eternal_utilized_balances.AA.add(new_AA_amount);
eternal_utilized_balances.A = eternal_utilized_balances.A.add(new_A_amount);
// Record vdsec for tranche S and new dsec for tranche AA and A
tranche_total_vdsec_AA[epoch][uint256(Tranche.S)] = tranche_total_vdsec_AA[epoch][uint256(Tranche.S)].add(get_seconds_until_next_removal_window(epoch).mul(new_AA_amount)); // Total AA vdsec owned by tranche S
tranche_total_vdsec_A[epoch][uint256(Tranche.S)] = tranche_total_vdsec_A[epoch][uint256(Tranche.S)].add(get_seconds_until_next_removal_window(epoch).mul(new_A_amount)); // Total A vdsec owned by tranche S
tranche_total_dsec[epoch][uint256(Tranche.AA)] = tranche_total_dsec[epoch][uint256(Tranche.AA)].add(get_seconds_until_next_removal_window(epoch).mul(new_AA_amount)); // Total dsec for tranche AA
tranche_total_dsec[epoch][uint256(Tranche.A)] = tranche_total_dsec[epoch][uint256(Tranche.A)].add(get_seconds_until_next_removal_window(epoch).mul(new_A_amount)); // Total dsec for tranche A
tranche_total_principal[epoch][uint256(Tranche.AA)] = tranche_total_principal[epoch][uint256(Tranche.AA)].add(new_AA_amount); // Add total principal for AA
tranche_total_principal[epoch][uint256(Tranche.A)] = tranche_total_principal[epoch][uint256(Tranche.A)].add(new_A_amount); // Add total principal for A
emit StrategicDeploy(adapter_address, amount, epoch);
// Add principal to adapter total
adapter_total_principal = adapter_total_principal.add(amount);
// Move base assets to adapter and deploy
IERC20(base_asset_address).safeTransfer(adapter_address, amount);
best_adapter.deploy_capital(amount);
}
/*** GOVERNANCE ***/
function set_governance(address to) external override {
require(msg.sender == governance, "must be governance");
governance = to;
}
/*** TIME UTILITY FUNCTIONS ***/
// Return whether or not we're in a removal period
// Removal window begins every epoch_cycle.duration seconds and lasts for epoch_cycle.removal_duration seconds
// Removal window is counted as part of the previous epoch (removal window for epoch 0 begins at 14 days and ends on 15 days - 1 second)
function is_removal_window(uint256 epoch) public view returns (bool) {
uint256 removal_window_begin = epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration));
uint256 removal_window_end = removal_window_begin.add(epoch_cycle.removal_duration);
// solhint-disable-next-line not-rely-on-time
return (block.timestamp >= removal_window_begin && block.timestamp < removal_window_end);
}
function get_removal_window_start(uint256 epoch) public view returns (uint256) {
return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration));
}
function get_removal_window_end(uint256 epoch) public view returns (uint256) {
return get_removal_window_start(epoch).add(epoch_cycle.removal_duration);
}
function get_current_epoch() public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return ( block.timestamp - epoch_cycle.start_date ) / epoch_cycle.duration;
}
function get_seconds_until_next_removal_window(uint256 epoch) public view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
return epoch_cycle.start_date.add(epoch.add(1).mul(epoch_cycle.duration)).sub(block.timestamp);
}
/*** GETTERS ***/
function get_epoch_cycle_params() external view override returns (uint256, uint256, uint256) {
return (epoch_cycle.start_date, epoch_cycle.duration, epoch_cycle.removal_duration);
}
function get_base_asset_address() external override view returns (address) {
return base_asset_address;
}
function get_governance() external override view returns (address) {
return governance;
}
function get_strategy_address() external override view returns (address) {
return address(strategy);
}
//***** ADAPTER FUNCTIONS *****//
// Delete adapters (v0: for v0 wind-down)
function delete_adapters() external override {
require(msg.sender == governance, "must be governance");
delete adapters;
}
} | Balance for each tranche that is not held within this pool but instead held on a platform via an adapter
| TrancheUint256 internal eternal_utilized_balances; | 6,770,576 | [
1,
13937,
364,
1517,
13637,
18706,
716,
353,
486,
15770,
3470,
333,
2845,
1496,
3560,
15770,
603,
279,
4072,
3970,
392,
4516,
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,
225,
840,
304,
18706,
5487,
5034,
2713,
225,
847,
82,
287,
67,
1367,
1235,
67,
70,
26488,
31,
565,
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
] |
pragma solidity ^0.4.15;
/*
https://galleass.io
by Austin Thomas Griffith
The Citizen represents workers in Galleass
They have genetics and characteristics and extend the ERC721 token standard
*/
import 'Galleasset.sol';
import 'NFT.sol';
contract Citizens is Galleasset, NFT {
string public constant name = "Galleass Citizen";
string public constant symbol = "G_CITIZEN";
constructor(address _galleass) Galleasset(_galleass) public {
//0 index should be a blank ship owned by no one
Citizen memory _citizen = Citizen({
status: 0,
data: 0,
x: 0,
y: 0,
tile: 0,
genes: 0x0000000000000000000000000000000000000000000000000000000000000000,
characteristics: 0x0000000000000000000000000000000000000000000000000000000000000000,
birth: 0
});
citizens.push(_citizen);
}
function () public {revert();}
struct Citizen{
uint8 status;
uint data;
uint16 x;
uint16 y;
uint8 tile;
bytes32 genes;
bytes32 characteristics;
uint64 birth;
}
Citizen[] private citizens;
//any Galleass contract that has transferCitizens can just move citizens from one owner to another
// this should probably only be given to the CitizensLib...
function galleassetTransferFrom(address _from,address _to,uint256 _tokenId) external {
require(_to != address(0));
require(_to != address(this));
require(_owns(_from, _tokenId));
require(hasPermission(msg.sender,"transferCitizens"));
_transfer(_from, _to, _tokenId);
}
//-------------- CitizenLib Access Functions -----------------------------------------------------//
/*
Citizen Lib needs full access to the storage of Citizens so we can keep the Citizen contract
storage intact but still upgrade the funtionality in the CitizenLib contract
*/
function createCitizen(address _owner,uint8 _status,uint _data,uint16 _x,uint16 _y, uint8 _tile, bytes32 _genes, bytes32 _characteristics) public isGalleasset("Citizens") returns (uint){
require(msg.sender == getContract("CitizensLib"));
_createCitizen(_owner,_status,_data,_x,_y,_tile,_genes,_characteristics);
}
function setStatus(uint _id,uint8 _status) public isGalleasset("Citizens") returns (bool){
require(msg.sender == getContract("CitizensLib"));
Citizen c = citizens[_id];
c.status = _status;
emit CitizenUpdate(_id,c.x,c.y,c.tile,tokenIndexToOwner[_id],c.status,c.data,c.genes,c.characteristics);
return true;
}
function setTile(uint _id,uint8 _tile) public isGalleasset("Citizens") returns (bool){
require(msg.sender == getContract("CitizensLib"));
Citizen c = citizens[_id];
c.tile = _tile;
emit CitizenUpdate(_id,c.x,c.y,c.tile,tokenIndexToOwner[_id],c.status,c.data,c.genes,c.characteristics);
return true;
}
function setData(uint _id,uint _data) public isGalleasset("Citizens") returns (bool){
require(msg.sender == getContract("CitizensLib"));
Citizen c = citizens[_id];
c.data = _data;
emit CitizenUpdate(_id,c.x,c.y,c.tile,tokenIndexToOwner[_id],c.status,c.data,c.genes,c.characteristics);
return true;
}
//------------------------------------------------------------------------------------------------//
function _createCitizen(address _owner,uint8 _status,uint _data,uint16 _x,uint16 _y, uint8 _tile, bytes32 _genes, bytes32 _characteristics) internal returns (uint){
Citizen memory _citizen = Citizen({
status: _status,
data: _data,
x:_x,
y:_y,
tile:_tile,
genes: _genes,
characteristics: _characteristics,
birth: uint64(block.number)
});
uint256 newCitizenId = citizens.push(_citizen) - 1;
_transfer(0, _owner, newCitizenId);
emit CitizenUpdate(newCitizenId,_citizen.x,_citizen.y,_citizen.tile,_owner,_citizen.status,_citizen.data,_citizen.genes,_citizen.characteristics);
return newCitizenId;
}
event CitizenUpdate(uint indexed id,uint16 indexed x, uint16 indexed y,uint8 tile,address owner,uint8 status,uint data,bytes32 genes,bytes32 characteristics);
function totalSupply() public view returns (uint) {
return citizens.length - 1;
}
function getToken(uint256 _id) public view returns (address owner,uint8 status,uint data,uint16 x,uint16 y,uint8 tile, bytes32 genes,bytes32 characteristics,uint64 birth) {
Citizen c = citizens[_id];
return (tokenIndexToOwner[_id],c.status,c.data,c.x,c.y,c.tile,c.genes,c.characteristics,c.birth);
}
function tokensOfOwner(address _owner) external view returns(uint256[]) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 total = totalSupply();
uint256 resultIndex = 0;
uint256 id;
for (id = 1; id <= total; id++) {
if (tokenIndexToOwner[id] == _owner) {
result[resultIndex] = id;
resultIndex++;
}
}
return result;
}
}
}
| 0 index should be a blank ship owned by no one | constructor(address _galleass) Galleasset(_galleass) public {
Citizen memory _citizen = Citizen({
status: 0,
data: 0,
x: 0,
y: 0,
tile: 0,
genes: 0x0000000000000000000000000000000000000000000000000000000000000000,
characteristics: 0x0000000000000000000000000000000000000000000000000000000000000000,
birth: 0
});
citizens.push(_citizen);
}
| 1,058,019 | [
1,
20,
770,
1410,
506,
279,
7052,
24316,
16199,
635,
1158,
1245,
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,
2867,
389,
75,
22534,
428,
13,
611,
22534,
9406,
24899,
75,
22534,
428,
13,
1071,
288,
203,
1377,
385,
305,
452,
275,
3778,
389,
71,
305,
452,
275,
273,
385,
305,
452,
275,
12590,
203,
3639,
1267,
30,
374,
16,
203,
3639,
501,
30,
374,
16,
203,
3639,
619,
30,
374,
16,
203,
3639,
677,
30,
374,
16,
203,
3639,
4769,
30,
374,
16,
203,
3639,
11423,
30,
374,
92,
12648,
12648,
12648,
12648,
12648,
12648,
12648,
12648,
16,
203,
3639,
29385,
30,
374,
92,
12648,
12648,
12648,
12648,
12648,
12648,
12648,
12648,
16,
203,
3639,
17057,
30,
374,
203,
1377,
15549,
203,
1377,
276,
305,
452,
773,
18,
6206,
24899,
71,
305,
452,
275,
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
] |
./partial_match/3/0x9a171daCec61b369e9af02326DAbebF9f97AF370/sources/prenup.sol | A function to change the Marriage status of the contract | function changeStatus(string memory _status) public ifOwner{
marriageStatus = _status;
}
| 5,161,892 | [
1,
37,
445,
358,
2549,
326,
490,
297,
27935,
1267,
434,
326,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2549,
1482,
12,
1080,
3778,
389,
2327,
13,
1071,
309,
5541,
95,
203,
3639,
21282,
27935,
1482,
273,
389,
2327,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x414cbF31c62D99515bfD66497B495a585b52F703/sources/Chappie.sol | reduce tax after marketing
| uint256 public _currentBuyTax=100; | 3,033,279 | [
1,
12498,
5320,
1839,
13667,
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,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
389,
2972,
38,
9835,
7731,
33,
6625,
31,
565,
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
] |
./full_match/7700/0x9B2a63F27661A468E2da22226b64A4914144f195/sources/contracts/interfaces/ICrocLpConduit.sol | @title LP conduit interface @notice Standard interface for contracts that accept and manage LP positions on behalf of end users. Typical example would be an ERC20 tracker for LP tokens. / | interface ICrocLpConduit {
function depositCrocLiq (address sender, bytes32 poolHash,
int24 lowerTick, int24 upperTick,
uint128 liq, uint72 mileage) external returns (bool);
function withdrawCrocLiq (address sender, bytes32 poolHash,
int24 lowerTick, int24 upperTick,
uint128 liq, uint72 mileage) external returns (bool);
}
| 4,651,433 | [
1,
14461,
356,
2544,
305,
1560,
225,
8263,
1560,
364,
20092,
716,
2791,
471,
10680,
511,
52,
6865,
603,
12433,
6186,
540,
434,
679,
3677,
18,
16973,
1706,
3454,
4102,
506,
392,
4232,
39,
3462,
9745,
364,
511,
52,
2430,
18,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
5831,
26899,
303,
71,
48,
84,
442,
2544,
305,
288,
203,
203,
565,
445,
443,
1724,
39,
303,
71,
48,
18638,
261,
2867,
5793,
16,
1731,
1578,
2845,
2310,
16,
203,
11794,
509,
3247,
2612,
6264,
16,
509,
3247,
3854,
6264,
16,
203,
11794,
2254,
10392,
4501,
85,
16,
2254,
9060,
312,
398,
410,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
565,
445,
598,
9446,
39,
303,
71,
48,
18638,
261,
2867,
5793,
16,
1731,
1578,
2845,
2310,
16,
203,
17311,
509,
3247,
2612,
6264,
16,
509,
3247,
3854,
6264,
16,
203,
17311,
2254,
10392,
4501,
85,
16,
2254,
9060,
312,
398,
410,
13,
3903,
1135,
261,
6430,
1769,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x122d162362ddB873DD9FFcb686629Af9B569A50a/sources/NFTStaking.sol | Make sure the user has at least one token staked before withdrawing Wallet must own the token they are trying to withdraw Update the rewards for this user, as the amount of rewards decreases with less tokens Find the index of this token id in the stakedTokens array | function withdraw(uint256 _tokenId) external nonReentrant {
require(
stakers[msg.sender].amountStaked > 0,
"You have no tokens staked!"
);
require(
stakerAddress[_tokenId] == msg.sender,
"You don't own this token!"
);
uint256 rewards = calculateRewards(msg.sender);
stakers[msg.sender].unclaimedRewards += rewards;
uint256 index = 0;
for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) {
if (stakers[msg.sender].stakedTokens[i].tokenId == _tokenId) {
index = i;
break;
}
}
}
| 1,912,393 | [
1,
6464,
3071,
326,
729,
711,
622,
4520,
1245,
1147,
384,
9477,
1865,
598,
9446,
310,
20126,
1297,
4953,
326,
1147,
2898,
854,
8374,
358,
598,
9446,
2315,
326,
283,
6397,
364,
333,
729,
16,
487,
326,
3844,
434,
283,
6397,
23850,
3304,
598,
5242,
2430,
4163,
326,
770,
434,
333,
1147,
612,
316,
326,
384,
9477,
5157,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
598,
9446,
12,
11890,
5034,
389,
2316,
548,
13,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
203,
5411,
384,
581,
414,
63,
3576,
18,
15330,
8009,
8949,
510,
9477,
405,
374,
16,
203,
5411,
315,
6225,
1240,
1158,
2430,
384,
9477,
4442,
203,
3639,
11272,
203,
203,
3639,
2583,
12,
203,
5411,
384,
6388,
1887,
63,
67,
2316,
548,
65,
422,
1234,
18,
15330,
16,
203,
5411,
315,
6225,
2727,
1404,
4953,
333,
1147,
4442,
203,
3639,
11272,
203,
203,
3639,
2254,
5034,
283,
6397,
273,
4604,
17631,
14727,
12,
3576,
18,
15330,
1769,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
551,
80,
4581,
329,
17631,
14727,
1011,
283,
6397,
31,
203,
203,
3639,
2254,
5034,
770,
273,
374,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
384,
581,
414,
63,
3576,
18,
15330,
8009,
334,
9477,
5157,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
334,
581,
414,
63,
3576,
18,
15330,
8009,
334,
9477,
5157,
63,
77,
8009,
2316,
548,
422,
389,
2316,
548,
13,
288,
203,
7734,
770,
273,
277,
31,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
203,
203,
203,
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
] |
./full_match/42/0x0892a950333B050Ea5478944c0ef0b1Ed5d7EaA2/sources/contracts/new_masterch.sol | update wrapped token state | _claimReward(_pid);
| 9,601,752 | [
1,
2725,
5805,
1147,
919,
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,
3639,
389,
14784,
17631,
1060,
24899,
6610,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/421613/0x620e20d91C9b0e11ecAE439E7b85138DA2a1003F/sources/contracts/libs/Slices.sol | @dev Modifies `self` to contain the part of the string from the start of `self` to the end of the first occurrence of `needle`. If `needle` is not found, `self` is set to the empty Slice. @param self The Slice to search and modify. @param needle The text to search for. @return `self`./ | function rfind(Slice memory self, Slice memory needle) internal pure returns (Slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
| 16,825,244 | [
1,
1739,
5032,
1375,
2890,
68,
358,
912,
326,
1087,
434,
326,
533,
628,
326,
787,
434,
1377,
1375,
2890,
68,
358,
326,
679,
434,
326,
1122,
13083,
434,
1375,
14891,
298,
8338,
971,
1375,
14891,
298,
68,
1377,
353,
486,
1392,
16,
1375,
2890,
68,
353,
444,
358,
326,
1008,
10506,
18,
225,
365,
1021,
10506,
358,
1623,
471,
5612,
18,
225,
9936,
1021,
977,
358,
1623,
364,
18,
327,
1375,
2890,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
31257,
12,
5959,
3778,
365,
16,
10506,
3778,
9936,
13,
2713,
16618,
1135,
261,
5959,
3778,
13,
288,
203,
3639,
2254,
6571,
273,
31257,
5263,
12,
2890,
6315,
1897,
16,
365,
6315,
6723,
16,
9936,
6315,
1897,
16,
9936,
6315,
6723,
1769,
203,
3639,
365,
6315,
1897,
273,
6571,
300,
365,
6315,
6723,
31,
203,
3639,
327,
365,
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
] |
// Copyright (C) 2020 Zerion Inc. <https://zerion.io>
//
// 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 <https://www.gnu.org/licenses/>.
//
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity 0.7.3;
pragma experimental ABIEncoderV2;
import {
TransactionData,
Action,
AbsoluteTokenAmount,
Fee,
TokenAmount
} from "../shared/Structs.sol";
import { ECDSA } from "../shared/ECDSA.sol";
contract SignatureVerifier {
mapping(bytes32 => mapping(address => bool)) internal isHashUsed_;
bytes32 internal immutable nameHash_;
bytes32 internal constant DOMAIN_SEPARATOR_TYPEHASH =
keccak256(
abi.encodePacked(
"EIP712Domain(",
"string name,",
"uint256 chainId,",
"address verifyingContract",
")"
)
);
bytes32 internal constant TX_DATA_TYPEHASH =
keccak256(
abi.encodePacked(
TX_DATA_ENCODED_TYPE,
ABSOLUTE_TOKEN_AMOUNT_ENCODED_TYPE,
ACTION_ENCODED_TYPE,
FEE_ENCODED_TYPE,
TOKEN_AMOUNT_ENCODED_TYPE
)
);
bytes32 internal constant ABSOLUTE_TOKEN_AMOUNT_TYPEHASH =
keccak256(ABSOLUTE_TOKEN_AMOUNT_ENCODED_TYPE);
bytes32 internal constant ACTION_TYPEHASH =
keccak256(abi.encodePacked(ACTION_ENCODED_TYPE, TOKEN_AMOUNT_ENCODED_TYPE));
bytes32 internal constant FEE_TYPEHASH = keccak256(FEE_ENCODED_TYPE);
bytes32 internal constant TOKEN_AMOUNT_TYPEHASH = keccak256(TOKEN_AMOUNT_ENCODED_TYPE);
bytes internal constant TX_DATA_ENCODED_TYPE =
abi.encodePacked(
"TransactionData(",
"Action[] actions,",
"TokenAmount[] inputs,",
"Fee fee,",
"AbsoluteTokenAmount[] requiredOutputs,",
"address account,",
"uint256 salt",
")"
);
bytes internal constant ABSOLUTE_TOKEN_AMOUNT_ENCODED_TYPE =
abi.encodePacked("AbsoluteTokenAmount(", "address token,", "uint256 amount", ")");
bytes internal constant ACTION_ENCODED_TYPE =
abi.encodePacked(
"Action(",
"bytes32 protocolAdapterName,",
"uint8 actionType,",
"TokenAmount[] tokenAmounts,",
"bytes data",
")"
);
bytes internal constant FEE_ENCODED_TYPE =
abi.encodePacked("Fee(", "uint256 share,", "address beneficiary", ")");
bytes internal constant TOKEN_AMOUNT_ENCODED_TYPE =
abi.encodePacked(
"TokenAmount(",
"address token,",
"uint256 amount,",
"uint8 amountType",
")"
);
constructor(string memory name) {
nameHash_ = keccak256(abi.encodePacked(name));
}
/**
* @param hash Hash to be checked.
* @param account Address of the hash will be checked for.
* @return True if hash has already been used by this account address.
*/
function isHashUsed(bytes32 hash, address account) public view returns (bool) {
return isHashUsed_[hash][account];
}
/**
* @param hashedData Hash to be checked.
* @param signature EIP-712 signature.
* @return Account that signed the hashed data.
*/
function getAccountFromSignature(bytes32 hashedData, bytes memory signature)
public
pure
returns (address payable)
{
return payable(ECDSA.recover(hashedData, signature));
}
/**
* @param data TransactionData struct to be hashed.
* @return TransactionData struct hashed with domainSeparator.
*/
function hashData(TransactionData memory data) public view returns (bytes32) {
bytes32 domainSeparator =
keccak256(
abi.encode(DOMAIN_SEPARATOR_TYPEHASH, nameHash_, getChainId(), address(this))
);
return
keccak256(abi.encodePacked(bytes1(0x19), bytes1(0x01), domainSeparator, hash(data)));
}
/**
* @dev Marks hash as used by the given account.
* @param hash Hash to be marked is used.
* @param account Account using the hash.
*/
function markHashUsed(bytes32 hash, address account) internal {
require(!isHashUsed_[hash][account], "SV: used hash!");
isHashUsed_[hash][account] = true;
}
/**
* @param data TransactionData struct to be hashed.
* @return Hashed TransactionData struct.
*/
function hash(TransactionData memory data) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
TX_DATA_TYPEHASH,
hash(data.actions),
hash(data.inputs),
hash(data.fee),
hash(data.requiredOutputs),
data.account,
data.salt
)
);
}
/**
* @dev Hashes Action structs list.
* @param actions Action structs list to be hashed.
* @return Hashed Action structs list.
*/
function hash(Action[] memory actions) internal pure returns (bytes32) {
bytes memory actionsData = new bytes(0);
uint256 length = actions.length;
for (uint256 i = 0; i < length; i++) {
actionsData = abi.encodePacked(
actionsData,
keccak256(
abi.encode(
ACTION_TYPEHASH,
actions[i].protocolAdapterName,
actions[i].actionType,
hash(actions[i].tokenAmounts),
keccak256(actions[i].data)
)
)
);
}
return keccak256(actionsData);
}
/**
* @dev Hashes TokenAmount structs list.
* @param tokenAmounts TokenAmount structs list to be hashed.
* @return Hashed TokenAmount structs list.
*/
function hash(TokenAmount[] memory tokenAmounts) internal pure returns (bytes32) {
bytes memory tokenAmountsData = new bytes(0);
uint256 length = tokenAmounts.length;
for (uint256 i = 0; i < length; i++) {
tokenAmountsData = abi.encodePacked(
tokenAmountsData,
keccak256(
abi.encode(
TOKEN_AMOUNT_TYPEHASH,
tokenAmounts[i].token,
tokenAmounts[i].amount,
tokenAmounts[i].amountType
)
)
);
}
return keccak256(tokenAmountsData);
}
/**
* @dev Hashes Fee struct.
* @param fee Fee struct to be hashed.
* @return Hashed Fee struct.
*/
function hash(Fee memory fee) internal pure returns (bytes32) {
return keccak256(abi.encode(FEE_TYPEHASH, fee.share, fee.beneficiary));
}
/**
* @dev Hashes AbsoluteTokenAmount structs list.
* @param absoluteTokenAmounts AbsoluteTokenAmount structs list to be hashed.
* @return Hashed AbsoluteTokenAmount structs list.
*/
function hash(AbsoluteTokenAmount[] memory absoluteTokenAmounts)
internal
pure
returns (bytes32)
{
bytes memory absoluteTokenAmountsData = new bytes(0);
uint256 length = absoluteTokenAmounts.length;
for (uint256 i = 0; i < length; i++) {
absoluteTokenAmountsData = abi.encodePacked(
absoluteTokenAmountsData,
keccak256(
abi.encode(
ABSOLUTE_TOKEN_AMOUNT_TYPEHASH,
absoluteTokenAmounts[i].token,
absoluteTokenAmounts[i].amount
)
)
);
}
return keccak256(absoluteTokenAmountsData);
}
/**
* @return Current chain ID.
*/
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
| * @return Current chain ID./ | function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
| 12,851,673 | [
1,
2463,
6562,
2687,
1599,
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
] | [
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,
30170,
548,
1435,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
2687,
548,
31,
203,
203,
3639,
19931,
288,
203,
5411,
2687,
548,
519,
2687,
350,
1435,
203,
3639,
289,
203,
203,
3639,
327,
2687,
548,
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
] |
/*
This file is part of The Colony Network.
The Colony Network 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.
The Colony Network 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 The Colony Network. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.23;
pragma experimental "v0.5.0";
import "../lib/dappsys/math.sol";
import "./IColonyNetwork.sol";
import "./PatriciaTree/PatriciaTreeProofs.sol";
import "./ITokenLocking.sol";
import "./ReputationMiningCycleStorage.sol";
// TODO (post CCv1, possibly never): Can we handle all possible disputes regarding the very first hash that should be set?
// Currently, at the very least, we can't handle a dispute if the very first entry is disputed.
// A possible workaround would be to 'kick off' reputation mining with a known dummy state...
// Given the approach we a taking for launch, we are able to guarantee that we are the only reputation miner for 100+ of the first cycles, even if we decided to lengthen a cycle length. As a result, maybe we just don't care about this special case?
contract ReputationMiningCycleRespond is ReputationMiningCycleStorage, PatriciaTreeProofs, DSMath {
/// @notice A modifier that checks if the challenge corresponding to the hash in the passed `round` and `id` is open
/// @param round The round number of the hash under consideration
/// @param idx The index in the round of the hash under consideration
modifier challengeOpen(uint256 round, uint256 idx) {
// Check the binary search has finished, but not necessarily confirmed
require(disputeRounds[round][idx].lowerBound == disputeRounds[round][idx].upperBound, "colony-reputation-mining-challenge-closed");
// Check the binary search result has been confirmed
require(
2**(disputeRounds[round][idx].challengeStepCompleted-2)>disputeRounds[round][idx].jrhNnodes,
"colony-reputation-mining-binary-search-result-not-confirmed"
);
// Check that we have not already responded to the challenge
require(
2**(disputeRounds[round][idx].challengeStepCompleted-3)<=disputeRounds[round][idx].jrhNnodes,
"colony-reputation-mining-challenge-already-responded"
);
_;
}
uint constant U_ROUND = 0;
uint constant U_IDX = 1;
uint constant U_REPUTATION_BRANCH_MASK = 2;
uint constant U_AGREE_STATE_NNODES = 3;
uint constant U_AGREE_STATE_BRANCH_MASK = 4;
uint constant U_DISAGREE_STATE_NNODES = 5;
uint constant U_DISAGREE_STATE_BRANCH_MASK = 6;
uint constant U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK = 7;
uint constant U_REQUIRE_REPUTATION_CHECK = 8;
uint constant U_LOG_ENTRY_NUMBER = 9;
uint constant U_DECAY_TRANSITION = 10;
uint constant DECAY_NUMERATOR = 992327946262944; // 24-hr mining cycles
uint constant DECAY_DENOMINATOR = 1000000000000000;
function respondToChallenge(
uint256[11] u, //An array of 11 UINT Params, ordered as given above.
bytes _reputationKey,
bytes32[] reputationSiblings,
bytes agreeStateReputationValue,
bytes32[] agreeStateSiblings,
bytes disagreeStateReputationValue,
bytes32[] disagreeStateSiblings,
bytes previousNewReputationKey,
bytes previousNewReputationValue,
bytes32[] previousNewReputationSiblings
) public
challengeOpen(u[U_ROUND], u[U_IDX])
{
u[U_REQUIRE_REPUTATION_CHECK] = 0;
u[U_DECAY_TRANSITION] = 0;
// TODO: More checks that this is an appropriate time to respondToChallenge (maybe in modifier);
/* bytes32 jrh = disputeRounds[round][idx].jrh; */
// The contract knows
// 1. the jrh for this submission
// 2. The first index where this submission and its opponent differ.
// Need to prove
// 1. The reputation that is updated that we disagree on's value, before the first index
// where we differ, and in the first index where we differ.
// 2. That no other changes are made to the reputation state. The proof for those
// two reputations in (1) is therefore required to be the same.
// 3. That our 'after' value is correct. This is done by doing the calculation on-chain, perhaps
// after looking up the corresponding entry in the reputation update log (the alternative is
// that it's a decay calculation - not yet implemented.)
// Check the supplied key is appropriate.
checkKey(u, _reputationKey, agreeStateReputationValue);
// Prove the reputation's starting value is in some state, and that state is in the appropriate index in our JRH
proveBeforeReputationValue(u, _reputationKey, reputationSiblings, agreeStateReputationValue, agreeStateSiblings);
// Prove the reputation's final value is in a particular state, and that state is in our JRH in the appropriate index (corresponding to the first disagreement between these miners)
// By using the same branchMask and siblings, we know that no other changes to the reputation state tree have been slipped in.
proveAfterReputationValue(u, _reputationKey, reputationSiblings, disagreeStateReputationValue, disagreeStateSiblings);
// Perform the reputation calculation ourselves.
performReputationCalculation(u, agreeStateReputationValue, disagreeStateReputationValue, previousNewReputationValue);
// Check the supplied previousNewRepuation is, in fact, in the same reputation state as the agreeState0
checkPreviousReputationInState(
u,
agreeStateSiblings,
previousNewReputationKey,
previousNewReputationValue,
previousNewReputationSiblings);
saveProvedReputation(u, previousNewReputationValue);
// If everthing checked out, note that we've responded to the challenge.
disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1;
disputeRounds[u[U_ROUND]][u[U_IDX]].lastResponseTimestamp = now;
// Safety net?
/* if (disputeRounds[round][idx].challengeStepCompleted==disputeRounds[round][opponentIdx].challengeStepCompleted){
// Freeze the reputation mining system.
} */
}
/////////////////////////
// Internal functions
/////////////////////////
function checkKey(uint256[11] u, bytes memory _reputationKey, bytes memory _reputationValue) internal {
// If the state transition we're checking is less than the number of nodes in the currently accepted state, it's a decay transition
// Otherwise, look up the corresponding entry in the reputation log.
uint256 updateNumber = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
if (updateNumber < IColonyNetwork(colonyNetworkAddress).getReputationRootHashNNodes()) {
checkKeyDecay(updateNumber, _reputationValue);
u[U_DECAY_TRANSITION] = 1;
} else {
checkKeyLogEntry(u[U_ROUND], u[U_IDX], u[U_LOG_ENTRY_NUMBER], _reputationKey);
}
}
function checkKeyDecay(uint256 _updateNumber, bytes memory _reputationValue) internal {
uint256 uid;
bytes memory reputationValue = new bytes(64);
reputationValue = _reputationValue;
assembly {
// NB first 32 bytes contain the length of the bytes object, so we are still correctly loading the second 32 bytes of the
// reputationValue, which contains the UID
uid := mload(add(reputationValue,64))
}
// We check that the reputation UID is right for the decay transition being disputed.
// The key is then implicitly checked when they prove that the key+value they supplied is in the
// right intermediate state in their justification tree.
require(uid-1 == _updateNumber, "colony-reputation-mining-uid-not-decay");
}
function checkKeyLogEntry(uint256 round, uint256 idx, uint256 logEntryNumber, bytes memory _reputationKey) internal {
uint256 updateNumber = disputeRounds[round][idx].lowerBound - 1 - IColonyNetwork(colonyNetworkAddress).getReputationRootHashNNodes();
ReputationLogEntry storage logEntry = reputationUpdateLog[logEntryNumber];
// Check that the supplied log entry corresponds to this update number
require(updateNumber >= logEntry.nPreviousUpdates, "colony-reputation-mining-update-number-part-of-previous-log-entry-updates");
require(
updateNumber < logEntry.nUpdates + logEntry.nPreviousUpdates,
"colony-reputation-mining-update-number-part-of-following-log-entry-updates");
uint expectedSkillId;
address expectedAddress;
(expectedSkillId, expectedAddress) = getExpectedSkillIdAndAddress(logEntry, updateNumber);
bytes memory reputationKey = new bytes(20+32+20);
reputationKey = _reputationKey;
address colonyAddress;
address userAddress;
uint256 skillId;
assembly {
colonyAddress := mload(add(reputationKey,20)) // 20, not 32, because we're copying in to a slot that will be interpreted as an address.
// which will truncate the leftmost 12 bytes
skillId := mload(add(reputationKey, 52))
userAddress := mload(add(reputationKey,72)) // 72, not 84, for the same reason as above. Is this being too clever? I don't think there are
// any unintended side effects here, but I'm not quite confortable enough with EVM's stack to be sure.
// Not sure what the alternative would be anyway.
}
require(expectedAddress == userAddress, "colony-reputation-mining-user-address-mismatch");
require(logEntry.colony == colonyAddress, "colony-reputation-mining-colony-address-mismatch");
require(expectedSkillId == skillId, "colony-reputation-mining-skill-id-mismatch");
}
function getExpectedSkillIdAndAddress(ReputationLogEntry storage logEntry, uint256 updateNumber) internal view
returns (uint256 expectedSkillId, address expectedAddress)
{
// Work out the expected userAddress and skillId for this updateNumber in this logEntry.
if ((updateNumber - logEntry.nPreviousUpdates + 1) <= logEntry.nUpdates / 2 ) {
// Then we're updating a colony-wide total, so we expect an address of 0x0
expectedAddress = 0x0;
} else {
// We're updating a user-specific total
expectedAddress = logEntry.user;
}
// Expected skill Id
// We update skills in the order children, then parents, then the skill listed in the log itself.
// If the amount in the log is positive, then no children are being updated.
uint nParents;
(nParents, , ) = IColonyNetwork(colonyNetworkAddress).getSkill(logEntry.skillId);
uint nChildUpdates;
if (logEntry.amount >= 0) { // solium-disable-line no-empty-blocks, whitespace
// Then we have no child updates to consider
} else {
nChildUpdates = logEntry.nUpdates/2 - 1 - nParents;
// NB This is not necessarily the same as nChildren. However, this is the number of child updates
// that this entry in the log was expecting at the time it was created.
}
uint256 relativeUpdateNumber = (updateNumber - logEntry.nPreviousUpdates) % (logEntry.nUpdates/2);
if (relativeUpdateNumber < nChildUpdates) {
expectedSkillId = IColonyNetwork(colonyNetworkAddress).getChildSkillId(logEntry.skillId, relativeUpdateNumber);
} else if (relativeUpdateNumber < (nChildUpdates+nParents)) {
expectedSkillId = IColonyNetwork(colonyNetworkAddress).getParentSkillId(logEntry.skillId, relativeUpdateNumber - nChildUpdates);
} else {
expectedSkillId = logEntry.skillId;
}
}
function proveBeforeReputationValue(
uint256[11] u,
bytes _reputationKey,
bytes32[] reputationSiblings,
bytes agreeStateReputationValue,
bytes32[] agreeStateSiblings
) internal
{
bytes32 jrh = disputeRounds[u[U_ROUND]][u[U_IDX]].jrh;
// We binary searched to the first disagreement, so the last agreement is the one before.
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
uint256 reputationValue;
assembly {
reputationValue := mload(add(agreeStateReputationValue, 32))
}
bytes32 reputationRootHash = getImpliedRoot(_reputationKey, agreeStateReputationValue, u[U_REPUTATION_BRANCH_MASK], reputationSiblings);
bytes memory jhLeafValue = new bytes(64);
bytes memory lastAgreeIdxBytes = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
let x := mload(add(u, mul(32,3))) // 3 = U_AGREE_STATE_NNODES. Constants not supported by inline solidity
mstore(add(jhLeafValue, 0x40), x)
mstore(add(lastAgreeIdxBytes, 0x20), lastAgreeIdx)
}
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions
// agree on.
bytes32 impliedRoot = getImpliedRoot(lastAgreeIdxBytes, jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
if (reputationValue == 0 && impliedRoot != jrh) {
// This implies they are claiming that this is a new hash.
return;
}
require(impliedRoot == jrh, "colony-reputation-mining-invalid-before-reputation-proof");
// They've actually verified whatever they claimed. We increment their challengeStepCompleted by one to indicate this.
// In the event that our opponent lied about this reputation not existing yet in the tree, they will both complete
// a call to respondToChallenge, but we will have a higher challengeStepCompleted value, and so they will be the ones
// eliminated.
disputeRounds[u[U_ROUND]][u[U_IDX]].challengeStepCompleted += 1;
// I think this trick can be used exactly once, and only because this is the last function to be called in the challege,
// and I'm choosing to use it here. I *think* this is okay, because the only situation
// where we don't prove anything with merkle proofs in this whole dance is here.
}
function proveAfterReputationValue(
uint256[11] u,
bytes _reputationKey,
bytes32[] reputationSiblings,
bytes disagreeStateReputationValue,
bytes32[] disagreeStateSiblings
) internal view
{
bytes32 jrh = disputeRounds[u[U_ROUND]][u[U_IDX]].jrh;
uint256 firstDisagreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound;
bytes32 reputationRootHash = getImpliedRoot(_reputationKey, disagreeStateReputationValue, u[U_REPUTATION_BRANCH_MASK], reputationSiblings);
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions
// agree on.
bytes memory jhLeafValue = new bytes(64);
bytes memory firstDisagreeIdxBytes = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
let x := mload(add(u, mul(32,5))) // 5 = U_DISAGREE_STATE_NNODES. Constants not supported by inline solidity.
mstore(add(jhLeafValue, 0x40), x)
mstore(add(firstDisagreeIdxBytes, 0x20), firstDisagreeIdx)
}
bytes32 impliedRoot = getImpliedRoot(firstDisagreeIdxBytes, jhLeafValue, u[U_DISAGREE_STATE_BRANCH_MASK], disagreeStateSiblings);
require(jrh==impliedRoot, "colony-reputation-mining-invalid-after-reputation-proof");
}
function performReputationCalculation(
uint256[11] u,
bytes agreeStateReputationValueBytes,
bytes disagreeStateReputationValueBytes,
bytes previousNewReputationValueBytes
) internal view
{
// TODO: Possibility of reputation loss - child reputations do not lose the whole of logEntry.amount, but the same fraction logEntry amount is of the user's reputation in skill given by logEntry.skillId
ReputationLogEntry storage logEntry = reputationUpdateLog[u[U_LOG_ENTRY_NUMBER]];
uint256 agreeStateReputationValue;
uint256 disagreeStateReputationValue;
uint256 agreeStateReputationUID;
uint256 disagreeStateReputationUID;
assembly {
agreeStateReputationValue := mload(add(agreeStateReputationValueBytes, 32))
disagreeStateReputationValue := mload(add(disagreeStateReputationValueBytes, 32))
agreeStateReputationUID := mload(add(agreeStateReputationValueBytes, 64))
disagreeStateReputationUID := mload(add(disagreeStateReputationValueBytes, 64))
}
if (agreeStateReputationUID != 0) {
// i.e. if this was an existing reputation, then require that the ID hasn't changed.
require(agreeStateReputationUID==disagreeStateReputationUID, "colony-reputation-mining-uid-changed-for-existing-reputation");
} else {
uint256 previousNewReputationUID;
assembly {
previousNewReputationUID := mload(add(previousNewReputationValueBytes, 64))
}
require(previousNewReputationUID + 1 == disagreeStateReputationUID, "colony-reputation-mining-new-uid-incorrect");
}
// We don't care about underflows for the purposes of comparison, but for the calculation we deem 'correct'.
// i.e. a reputation can't be negative.
if (u[U_DECAY_TRANSITION] == 1) {
// Very large reputation decays are calculated the 'other way around' to avoid overflows.
if (agreeStateReputationValue > uint256(2**256 - 1)/uint256(10**15)) {
require(disagreeStateReputationValue == (agreeStateReputationValue/DECAY_DENOMINATOR)*DECAY_NUMERATOR, "colony-reputation-mining-decay-incorrect");
} else {
require(disagreeStateReputationValue == (agreeStateReputationValue*DECAY_NUMERATOR)/DECAY_DENOMINATOR, "colony-reputation-mining-decay-incorrect");
}
} else {
if (logEntry.amount < 0 && uint(logEntry.amount * -1) > agreeStateReputationValue ) {
require(disagreeStateReputationValue == 0, "colony-reputation-mining-reputation-value-non-zero");
} else if (uint(logEntry.amount) + agreeStateReputationValue < agreeStateReputationValue) {
// We also don't allow reputation to overflow
require(disagreeStateReputationValue == 2**256 - 1, "colony-reputation-mining-reputation-not-max-uint");
} else {
// TODO: Is this safe? I think so, because even if there's over/underflows, they should
// still be the same number.
require(int(agreeStateReputationValue)+logEntry.amount == int(disagreeStateReputationValue), "colony-reputation-mining-invalid-newest-reputation-proof");
}
}
}
function checkPreviousReputationInState(
uint256[11] u,
bytes32[] agreeStateSiblings,
bytes previousNewReputationKey,
bytes previousNewReputationValue,
bytes32[] previousNewReputationSiblings
) internal view
{
// We binary searched to the first disagreement, so the last agreement is the one before
uint256 lastAgreeIdx = disputeRounds[u[U_ROUND]][u[U_IDX]].lowerBound - 1;
bytes32 reputationRootHash = getImpliedRoot(
previousNewReputationKey,
previousNewReputationValue,
u[U_PREVIOUS_NEW_REPUTATION_BRANCH_MASK],
previousNewReputationSiblings
);
bytes memory jhLeafValue = new bytes(64);
bytes memory lastAgreeIdxBytes = new bytes(32);
assembly {
mstore(add(jhLeafValue, 0x20), reputationRootHash)
let x := mload(add(u, mul(32,3))) // 3 = U_AGREE_STATE_NNODES. Constants not supported by inline assembly
mstore(add(jhLeafValue, 0x40), x)
mstore(add(lastAgreeIdxBytes, 0x20), lastAgreeIdx)
}
// Prove that state is in our JRH, in the index corresponding to the last state that the two submissions agree on
bytes32 impliedRoot = getImpliedRoot(lastAgreeIdxBytes, jhLeafValue, u[U_AGREE_STATE_BRANCH_MASK], agreeStateSiblings);
require(impliedRoot == disputeRounds[u[U_ROUND]][u[U_IDX]].jrh, "colony-reputation-mining-last-state-disagreement");
}
function saveProvedReputation(uint256[11] u, bytes previousNewReputationValue) internal {
uint256 previousReputationUID;
assembly {
previousReputationUID := mload(add(previousNewReputationValue,0x40))
}
// Require that it is at least plausible
uint256 delta = disputeRounds[u[U_ROUND]][u[U_IDX]].intermediateReputationNNodes - previousReputationUID;
// Could be zero if this is an update to an existing reputation, or it could be 1 if we have just added a new
// reputation. Anything else is inconsistent.
// We don't care about over/underflowing, and don't want to use `sub` so that this require message is returned.
require(delta == 0 || delta == 1, "colony-reputation-mining-proved-uid-inconsistent");
// Save the index for tiebreak scenarios later.
disputeRounds[u[U_ROUND]][u[U_IDX]].provedPreviousReputationUID = previousReputationUID;
}
}
| i.e. if this was an existing reputation, then require that the ID hasn't changed. | if (agreeStateReputationUID != 0) {
require(agreeStateReputationUID==disagreeStateReputationUID, "colony-reputation-mining-uid-changed-for-existing-reputation");
uint256 previousNewReputationUID;
assembly {
previousNewReputationUID := mload(add(previousNewReputationValueBytes, 64))
}
require(previousNewReputationUID + 1 == disagreeStateReputationUID, "colony-reputation-mining-new-uid-incorrect");
}
| 12,652,153 | [
1,
77,
18,
73,
18,
309,
333,
1703,
392,
2062,
283,
458,
367,
16,
1508,
2583,
716,
326,
1599,
13342,
1404,
3550,
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
] | [
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,
565,
309,
261,
346,
992,
1119,
426,
458,
367,
3060,
480,
374,
13,
288,
203,
1377,
2583,
12,
346,
992,
1119,
426,
458,
367,
3060,
631,
2251,
346,
992,
1119,
426,
458,
367,
3060,
16,
315,
1293,
6598,
17,
266,
458,
367,
17,
1154,
310,
17,
1911,
17,
6703,
17,
1884,
17,
11711,
17,
266,
458,
367,
8863,
203,
1377,
2254,
5034,
2416,
1908,
426,
458,
367,
3060,
31,
203,
1377,
19931,
288,
203,
3639,
2416,
1908,
426,
458,
367,
3060,
519,
312,
945,
12,
1289,
12,
11515,
1908,
426,
458,
367,
620,
2160,
16,
5178,
3719,
203,
1377,
289,
203,
1377,
2583,
12,
11515,
1908,
426,
458,
367,
3060,
397,
404,
422,
1015,
346,
992,
1119,
426,
458,
367,
3060,
16,
315,
1293,
6598,
17,
266,
458,
367,
17,
1154,
310,
17,
2704,
17,
1911,
17,
267,
6746,
8863,
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/1/0x80497049b005Fd236591c3CD431DBD6E06eB1A31/sources/contracts/rewards/Staking.sol | @inheritdoc IStaking | function tokensToShares(uint256 _tokens) external view returns (uint256 shares_) {
uint256 _currentBalance = smardexToken.balanceOf(address(this));
_currentBalance += farming.pendingReward(CAMPAIGN_ID, address(this));
shares_ = _tokensToShares(_tokens, _currentBalance);
}
| 2,865,093 | [
1,
36,
10093,
467,
510,
6159,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2430,
774,
24051,
12,
11890,
5034,
389,
7860,
13,
3903,
1476,
1135,
261,
11890,
5034,
24123,
67,
13,
288,
203,
3639,
2254,
5034,
389,
2972,
13937,
273,
3029,
297,
561,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
389,
2972,
13937,
1011,
284,
4610,
310,
18,
9561,
17631,
1060,
12,
39,
2192,
4066,
10452,
67,
734,
16,
1758,
12,
2211,
10019,
203,
203,
3639,
24123,
67,
273,
389,
7860,
774,
24051,
24899,
7860,
16,
389,
2972,
13937,
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
] |
./full_match/80001/0x86c222a29BE67e0F59E554a6cEF21B645c7F4CD7/sources/_openzeppelin/contracts-upgradeable/utils/MulticallUpgradeable.sol | * @dev Provides a function to batch together multiple calls in a single external call. _Available since v4.1._/ | abstract contract MulticallUpgradeable is Initializable {
function __Multicall_init() internal onlyInitializing {
}
function __Multicall_init_unchained() internal onlyInitializing {
}
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = AddressUpgradeable.functionDelegateCall(address(this), data[i]);
}
return results;
}
function multicall(bytes[] calldata data) external virtual returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; i++) {
results[i] = AddressUpgradeable.functionDelegateCall(address(this), data[i]);
}
return results;
}
uint256[50] private __gap;
}
| 5,705,737 | [
1,
17727,
279,
445,
358,
2581,
9475,
3229,
4097,
316,
279,
2202,
3903,
745,
18,
389,
5268,
3241,
331,
24,
18,
21,
6315,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
7778,
335,
454,
10784,
429,
353,
10188,
6934,
288,
203,
203,
565,
445,
1001,
5049,
335,
454,
67,
2738,
1435,
2713,
1338,
29782,
288,
203,
565,
289,
203,
203,
565,
445,
1001,
5049,
335,
454,
67,
2738,
67,
4384,
8707,
1435,
2713,
1338,
29782,
288,
203,
565,
289,
203,
565,
445,
1778,
335,
454,
12,
3890,
8526,
745,
892,
501,
13,
3903,
5024,
1135,
261,
3890,
8526,
3778,
1686,
13,
288,
203,
3639,
1686,
273,
394,
1731,
8526,
12,
892,
18,
2469,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
501,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1686,
63,
77,
65,
273,
5267,
10784,
429,
18,
915,
9586,
1477,
12,
2867,
12,
2211,
3631,
501,
63,
77,
19226,
203,
3639,
289,
203,
3639,
327,
1686,
31,
203,
565,
289,
203,
203,
565,
445,
1778,
335,
454,
12,
3890,
8526,
745,
892,
501,
13,
3903,
5024,
1135,
261,
3890,
8526,
3778,
1686,
13,
288,
203,
3639,
1686,
273,
394,
1731,
8526,
12,
892,
18,
2469,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
501,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1686,
63,
77,
65,
273,
5267,
10784,
429,
18,
915,
9586,
1477,
12,
2867,
12,
2211,
3631,
501,
63,
77,
19226,
203,
3639,
289,
203,
3639,
327,
1686,
31,
203,
565,
289,
203,
203,
565,
2254,
5034,
63,
3361,
65,
3238,
1001,
14048,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.0 <0.6.0;
/*
Copyright 2016, Jordi Baylina
Contributor: Adrià Massanet <[email protected]>
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/>.
*/
import "./ERC20.sol";
import "./Owned.sol";
/// @dev `Escapable` is a base level contract built off of the `Owned`
/// contract; it creates an escape hatch function that can be called in an
/// emergency that will allow designated addresses to send any ether or tokens
/// held in the contract to an `escapeHatchDestination` as long as they were
/// not blacklisted
contract Escapable is Owned {
address payable public escapeHatchCaller;
address payable public escapeHatchDestination;
mapping (address=>bool) private escapeBlacklist; // Token contract addresses
/// @notice The Constructor assigns the `escapeHatchDestination` and the
/// `escapeHatchCaller`
/// @param _escapeHatchCaller The address of a trusted account or contract
/// to call `escapeHatch()` to send the ether in this contract to the
/// `escapeHatchDestination` it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
/// @param _escapeHatchDestination The address of a safe location (usu a
/// Multisig) to send the ether held in this contract; if a neutral address
/// is required, the WHG Multisig is an option:
/// 0x8Ff920020c8AD673661c8117f2855C384758C572
constructor (address payable _escapeHatchCaller, address payable _escapeHatchDestination) public {
escapeHatchCaller = _escapeHatchCaller;
escapeHatchDestination = _escapeHatchDestination;
}
/// @dev The addresses preassigned as `escapeHatchCaller` or `owner`
/// are the only addresses that can call a function with this modifier
modifier onlyEscapeHatchCallerOrOwner {
require ((msg.sender == escapeHatchCaller)||(msg.sender == owner));
_;
}
/// @notice Creates the blacklist of tokens that are not able to be taken
/// out of the contract; can only be done at the deployment, and the logic
/// to add to the blacklist will be in the constructor of a child contract
/// @param _token the token contract address that is to be blacklisted
function blacklistEscapeToken(address _token) internal {
escapeBlacklist[_token] = true;
emit EscapeHatchBlackistedToken(_token);
}
/// @notice Checks to see if `_token` is in the blacklist of tokens
/// @param _token the token address being queried
/// @return False if `_token` is in the blacklist and can't be taken out of
/// the contract via the `escapeHatch()`
function isTokenEscapable(address _token) view public returns (bool) {
return !escapeBlacklist[_token];
}
/// @notice The `escapeHatch()` should only be called as a last resort if a
/// security issue is uncovered or something unexpected happened
/// @param _token to transfer, use 0x0 for ether
function escapeHatch(address _token) public onlyEscapeHatchCallerOrOwner {
require(escapeBlacklist[_token]==false);
uint256 balance;
/// @dev Logic for ether
if (_token == 0x06Da25591CdF58758C4b3aBbFf18B092e4380B65) {
balance = 12;
escapeHatchDestination.transfer(balance);
emit EscapeHatchCalled(_token, balance);
return;
}
/// @dev Logic for tokens
ERC20 token = ERC20(_token);
balance = address(token).balance;
require(token.transfer(escapeHatchDestination, balance));
emit EscapeHatchCalled(_token, balance);
}
/// @notice Changes the address assigned to call `escapeHatch()`
/// @param _newEscapeHatchCaller The address of a trusted account or
/// contract to call `escapeHatch()` to send the value in this contract to
/// the `escapeHatchDestination`; it would be ideal that `escapeHatchCaller`
/// cannot move funds out of `escapeHatchDestination`
function changeHatchEscapeCaller(address payable _newEscapeHatchCaller) public onlyEscapeHatchCallerOrOwner {
escapeHatchCaller = _newEscapeHatchCaller;
}
event EscapeHatchBlackistedToken(address token);
event EscapeHatchCalled(address token, uint amount);
}
| @notice The Constructor assigns the `escapeHatchDestination` and the `escapeHatchCaller` @param _escapeHatchCaller The address of a trusted account or contract to call `escapeHatch()` to send the ether in this contract to the `escapeHatchDestination` it would be ideal that `escapeHatchCaller` cannot move funds out of `escapeHatchDestination` @param _escapeHatchDestination The address of a safe location (usu a Multisig) to send the ether held in this contract; if a neutral address is required, the WHG Multisig is an option: 0x8Ff920020c8AD673661c8117f2855C384758C572 | constructor (address payable _escapeHatchCaller, address payable _escapeHatchDestination) public {
escapeHatchCaller = _escapeHatchCaller;
escapeHatchDestination = _escapeHatchDestination;
}
| 1,807,985 | [
1,
1986,
11417,
22698,
326,
1375,
6939,
44,
505,
5683,
68,
471,
326,
225,
1375,
6939,
44,
505,
11095,
68,
225,
389,
6939,
44,
505,
11095,
1021,
1758,
434,
279,
13179,
2236,
578,
6835,
225,
358,
745,
1375,
6939,
44,
505,
20338,
358,
1366,
326,
225,
2437,
316,
333,
6835,
358,
326,
225,
1375,
6939,
44,
505,
5683,
68,
518,
4102,
506,
23349,
716,
1375,
6939,
44,
505,
11095,
68,
225,
2780,
3635,
284,
19156,
596,
434,
1375,
6939,
44,
505,
5683,
68,
225,
389,
6939,
44,
505,
5683,
1021,
1758,
434,
279,
4183,
2117,
261,
407,
89,
279,
225,
7778,
291,
360,
13,
358,
1366,
326,
225,
2437,
15770,
316,
333,
6835,
31,
309,
279,
22403,
287,
1758,
225,
353,
1931,
16,
326,
14735,
43,
7778,
291,
360,
353,
392,
1456,
30,
225,
374,
92,
28,
42,
74,
29,
6976,
3462,
71,
28,
1880,
9599,
5718,
9498,
71,
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,
565,
3885,
261,
2867,
8843,
429,
389,
6939,
44,
505,
11095,
16,
1758,
8843,
429,
389,
6939,
44,
505,
5683,
13,
1071,
288,
203,
3639,
4114,
44,
505,
11095,
273,
389,
6939,
44,
505,
11095,
31,
203,
3639,
4114,
44,
505,
5683,
273,
389,
6939,
44,
505,
5683,
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
] |
pragma solidity ^0.5.3;
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
mapping (address=>bool) private contractAuthorization;
//variables defining a airline
struct Airline {
bool isRegistered;
uint256 funds;
uint256 votes;
}
//private map holding registered airlines
mapping (address=>Airline) private airlines;
uint256 private _numAirlines = 0;
uint32 private _numFundedAirlines = 0;
//Consensus data
mapping (address=>address[]) private consensusMap;
//Insurance Struct
struct InsuranceContract{
address passenger;
string flight;
uint256 value;
bool redeemed;
bool payed;
}
/******************************
* Insurance Data *
******************************/
mapping(bytes32 => InsuranceContract) private insuredFlightsList;
mapping(string => address[]) private flightPassengersArray;
mapping(address => uint256) private passengerPayoutFunds;
//flight struct
struct Flight{
string name;
uint256 flightDateTime;
address airline;
uint8 status;
}
/****************************
* Flight Data *
*****************************/
//registered flights by flight name and airling
mapping(bytes32 => Flight) private registeredFlights;
/********************************************************************************************/
/* Flight Functions */
/********************************************************************************************/
/**
Register a flight
*/
function registerFlight(string calldata flightName, address airline, uint256 flightDateTime, uint8 flightStatus)
external
isAuthorizedCaller
requireIsOperational
{
Flight memory regFlight = Flight({
name: flightName,
flightDateTime: flightDateTime,
airline: airline,
status: flightStatus
});
bytes32 tmpKey = getKey(regFlight.name, regFlight.airline);
registeredFlights[tmpKey] = regFlight;
}
/**
Get Flight Info
*/
function getFlightInfo(string calldata flightName, address airline) view external requireIsOperational
isAuthorizedCaller returns(string memory, uint256, address, uint8 )
{
bytes32 tmpKey = getKey(flightName, airline);
require(registeredFlights[tmpKey].airline != address(0), "This flight is not registered.");
return( registeredFlights[tmpKey].name, registeredFlights[tmpKey].flightDateTime, registeredFlights[tmpKey].airline, registeredFlights[tmpKey].status);
}
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
contractAuthorization[msg.sender] = true;
//create insertion of first airline
airlines[msg.sender] = Airline(true, 0, 0);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireNotAlreadyRegistered(address toReg)
{
require(airlines[toReg].isRegistered, "Airline already registered!");
_;
}
/**
* @dev Modifier that requires the "authorized caller" account to be the function caller
*/
modifier isAuthorizedCaller()
{
require(contractAuthorization[msg.sender], "Caller is not authorized caller");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Set authorized callors
* @return A bool that is the current operating status
*/
function authorizeCaller(address dataContract) external requireContractOwner{
contractAuthorization[dataContract] = true;
}
/**
* @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 */
/********************************************************************************************/
function getKey(string memory name, address addr) pure internal returns(bytes32)
{
bytes32 tmpkey = keccak256(abi.encodePacked(name, addr));
return (tmpkey);
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address airlineAddress
)
isAuthorizedCaller
external
{
//
airlines[airlineAddress]=Airline({
isRegistered: true,
funds: 0,
votes: consensusMap[airlineAddress].length
});
_numAirlines = _numAirlines.add(1);
}
/**
* @dev deposit airline funds
* Can only be called from FlightSuretyApp contract
*
*/
function depositAirlineFunds(address depositor, uint256 funds)
isAuthorizedCaller
payable
external
{
airlines[depositor].funds = airlines[depositor].funds.add(funds);
}
/**
* @dev deposit airline funds
* Can only be called from FlightSuretyApp contract
*
*/
function setAirlineAsRegistered(address authorize)
isAuthorizedCaller
payable
external
{
airlines[authorize].isRegistered = true;
_numAirlines = _numAirlines.add(1);
}
/**
* @dev vote on airline consensus
* Can only be called from FlightSuretyApp contract
*
*/
function concensusVote(address airlineToAdd, address sponsorAirline)
isAuthorizedCaller
external
payable
returns(uint256)
{
if(consensusMap[airlineToAdd].length != 0){
for(uint i=0; i < consensusMap[airlineToAdd].length; i++){
require(consensusMap[airlineToAdd][i] != sponsorAirline, "Airline has already voted!");
}
}
consensusMap[airlineToAdd].push(sponsorAirline);
airlines[airlineToAdd].votes = airlines[airlineToAdd].votes.add(1);
return consensusMap[airlineToAdd].length;
}
/**
* @dev return total votes airline funds
* Can only be called from FlightSuretyApp contract
*
*/
function airlineTotalVotes(address airlineToAdd)
isAuthorizedCaller
external
view
returns(uint256)
{
return consensusMap[airlineToAdd].length;
}
/**
* @dev get current number of registered airlines
* Can only be called from FlightSuretyApp contract
*
*/
function getNumberRegisteredAirlines()
isAuthorizedCaller
view
external
returns(uint256)
{
return _numAirlines;
}
//this is here to make boilerplate test pass
function isAirline( address airlineAddress
)
isAuthorizedCaller
external
view
returns (bool)
{
Airline memory myAirline =airlines[airlineAddress];
bool out = false;
if(myAirline.isRegistered){
out = true;
}
return out;
}
//get current funds for airline
function getAirlineFunds( address airlineAddress
)
isAuthorizedCaller
external
view
returns (uint256)
{
Airline memory myAirline =airlines[airlineAddress];
uint256 theFunds = myAirline.funds;
return theFunds;
}
//get current funds for airline
function getAirline( address airlineAddress
)
isAuthorizedCaller
external
view
returns (bool, uint256, uint256)
{
Airline memory myAirline =airlines[airlineAddress];
return (myAirline.isRegistered, myAirline.funds, myAirline.votes);
}
/********************************************************************************************/
/* Insurance CONTRACT FUNCTIONS */
/********************************************************************************************/
/*
* Passenger Purchases Insurance
*/
function passengerPurchase(string calldata flight, address passenger) external payable isAuthorizedCaller{
//create a new contract
InsuranceContract memory insTmp = InsuranceContract({
passenger: passenger,
flight: flight,
value: msg.value,
redeemed: false,
payed: false
});
//keep track of it
bytes32 tmpkey = keccak256(abi.encodePacked(flight, passenger));
//keep list of insurance contracts by hashed flight Passenger pair
insuredFlightsList[tmpkey] = insTmp;
//keep a list of passengers with insurance by flight
flightPassengersArray[flight].push(passenger);
}
/*
* Get Insurance Contract
*/
function getInsuranceContract(string calldata flight, address passenger) external view isAuthorizedCaller
returns (address, string memory, uint256, bool, bool)
{
//create hashed flight Passenger pair
bytes32 tmpkey = keccak256(abi.encodePacked(flight, passenger));
return (insuredFlightsList[tmpkey].passenger, insuredFlightsList[tmpkey].flight, insuredFlightsList[tmpkey].value,
insuredFlightsList[tmpkey].redeemed, insuredFlightsList[tmpkey].payed);
}
/*
* credit passengers with flight insurance
*/
function creditByFlight(string calldata flight)external isAuthorizedCaller
{
//get passengers to be credited by flight
address[] memory psgArray = flightPassengersArray[flight];
//loop through passengers and credit
for(uint i = 0; i < psgArray.length; i++){
//get key for insurance contracts
bytes32 tmpkey = keccak256(abi.encodePacked(flight, psgArray[i]));
//get record
InsuranceContract storage psgInsContract = insuredFlightsList[tmpkey];
//add passenger to a list of passengers authorized to pay
//increase by insurance leverage 1.5 = (3*value)/2
uint256 tmpVal = psgInsContract.value.mul(3).div(2);
passengerPayoutFunds[psgInsContract.passenger] = tmpVal;
//mark contract as redeemed
psgInsContract.redeemed = true;
//update stored contract
insuredFlightsList[tmpkey] = psgInsContract;
}
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
)
external
payable
{
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
)
external
pure
{
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
)
external
pure
{
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund
(
)
public
payable
{
}
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()
external
payable
{
fund();
}
}
| *************************** Flight Data /registered flights by flight name and airling | mapping(bytes32 => Flight) private registeredFlights;
| 14,045,084 | [
1,
24243,
225,
1910,
1850,
342,
14327,
1183,
10730,
635,
25187,
508,
471,
23350,
2456,
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,
2874,
12,
3890,
1578,
516,
3857,
750,
13,
3238,
4104,
2340,
10730,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Simple interface for derivative price source oracle implementations
interface IDerivativePriceFeed {
function calcUnderlyingValues(address, uint256)
external
returns (address[] memory, uint256[] memory);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../staking-wrappers/convex-curve-lp/ConvexCurveLpStakingWrapperFactory.sol";
import "../IDerivativePriceFeed.sol";
/// @title ConvexCurveLpStakingWrapperPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for wrapped Convex-staked Curve LP tokens
contract ConvexCurveLpStakingWrapperPriceFeed is IDerivativePriceFeed {
ConvexCurveLpStakingWrapperFactory private immutable WRAPPER_FACTORY;
constructor(address _wrapperFactory) public {
WRAPPER_FACTORY = ConvexCurveLpStakingWrapperFactory(_wrapperFactory);
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
underlyings_ = new address[](1);
underlyings_[0] = WRAPPER_FACTORY.getCurveLpTokenForWrapper(_derivative);
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount;
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return WRAPPER_FACTORY.getCurveLpTokenForWrapper(_asset) != address(0);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title IStakingWrapper interface
/// @author Enzyme Council <[email protected]>
interface IStakingWrapper {
struct TotalHarvestData {
uint128 integral;
uint128 lastCheckpointBalance;
}
struct UserHarvestData {
uint128 integral;
uint128 claimableReward;
}
function claimRewardsFor(address _for)
external
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_);
function deposit(uint256 _amount) external;
function depositTo(address _to, uint256 _amount) external;
function withdraw(uint256 _amount, bool _claimRewards)
external
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_);
function withdrawTo(
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external;
function withdrawToOnBehalf(
address _onBehalf,
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external;
// STATE GETTERS
function getRewardTokenAtIndex(uint256 _index) external view returns (address rewardToken_);
function getRewardTokenCount() external view returns (uint256 count_);
function getRewardTokens() external view returns (address[] memory rewardTokens_);
function getTotalHarvestDataForRewardToken(address _rewardToken)
external
view
returns (TotalHarvestData memory totalHarvestData_);
function getUserHarvestDataForRewardToken(address _user, address _rewardToken)
external
view
returns (UserHarvestData memory userHarvestData_);
function isPaused() external view returns (bool isPaused_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../utils/AddressArrayLib.sol";
import "./IStakingWrapper.sol";
/// @title StakingWrapperBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for staking wrappers
/// @dev Can be used as a base for both standard deployments and proxy targets.
/// Draws on Convex's ConvexStakingWrapper implementation (https://github.com/convex-eth/platform/blob/main/contracts/contracts/wrappers/ConvexStakingWrapper.sol),
/// which is based on Curve.fi gauge wrappers (https://github.com/curvefi/curve-dao-contracts/tree/master/contracts/gauges/wrappers)
abstract contract StakingWrapperBase is IStakingWrapper, ERC20, ReentrancyGuard {
using AddressArrayLib for address[];
using SafeERC20 for ERC20;
using SafeMath for uint256;
event Deposited(address indexed from, address indexed to, uint256 amount);
event PauseToggled(bool isPaused);
event RewardsClaimed(
address caller,
address indexed user,
address[] rewardTokens,
uint256[] claimedAmounts
);
event RewardTokenAdded(address token);
event TotalHarvestIntegralUpdated(address indexed rewardToken, uint256 integral);
event TotalHarvestLastCheckpointBalanceUpdated(
address indexed rewardToken,
uint256 lastCheckpointBalance
);
event UserHarvestUpdated(
address indexed user,
address indexed rewardToken,
uint256 integral,
uint256 claimableReward
);
event Withdrawn(
address indexed caller,
address indexed from,
address indexed to,
uint256 amount
);
uint8 private constant DEFAULT_DECIMALS = 18;
uint256 private constant INTEGRAL_PRECISION = 1e18;
address internal immutable OWNER;
// Paused stops new deposits and checkpoints
bool private paused;
address[] private rewardTokens;
mapping(address => TotalHarvestData) private rewardTokenToTotalHarvestData;
mapping(address => mapping(address => UserHarvestData)) private rewardTokenToUserToHarvestData;
modifier onlyOwner() {
require(msg.sender == OWNER, "Only owner callable");
_;
}
constructor(
address _owner,
string memory _tokenName,
string memory _tokenSymbol
) public ERC20(_tokenName, _tokenSymbol) {
OWNER = _owner;
}
/// @notice Toggles pause for deposit and harvesting new rewards
/// @param _isPaused True if next state is paused, false if unpaused
function togglePause(bool _isPaused) external onlyOwner {
paused = _isPaused;
emit PauseToggled(_isPaused);
}
////////////////////////////
// DEPOSITOR INTERACTIONS //
////////////////////////////
// CLAIM REWARDS
/// @notice Claims all rewards for a given account
/// @param _for The account for which to claim rewards
/// @return rewardTokens_ The reward tokens
/// @return claimedAmounts_ The reward token amounts claimed
/// @dev Can be called off-chain to simulate the total harvestable rewards for a particular user
function claimRewardsFor(address _for)
external
override
nonReentrant
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
return __checkpointAndClaim(_for);
}
// DEPOSIT
/// @notice Deposits tokens to be staked, minting staking token to sender
/// @param _amount The amount of tokens to deposit
function deposit(uint256 _amount) external override {
__deposit(msg.sender, msg.sender, _amount);
}
/// @notice Deposits tokens to be staked, minting staking token to a specified account
/// @param _to The account to receive staking tokens
/// @param _amount The amount of tokens to deposit
function depositTo(address _to, uint256 _amount) external override {
__deposit(msg.sender, _to, _amount);
}
/// @dev Helper to deposit tokens to be staked
function __deposit(
address _from,
address _to,
uint256 _amount
) private nonReentrant {
require(!isPaused(), "__deposit: Paused");
// Checkpoint before minting
__checkpoint([_to, address(0)]);
_mint(_to, _amount);
__depositLogic(_from, _amount);
emit Deposited(_from, _to, _amount);
}
// WITHDRAWAL
/// @notice Withdraws staked tokens, returning tokens to the sender, and optionally claiming rewards
/// @param _amount The amount of tokens to withdraw
/// @param _claimRewards True if accrued rewards should be claimed
/// @return rewardTokens_ The reward tokens
/// @return claimedAmounts_ The reward token amounts claimed
/// @dev Setting `_claimRewards` to true will save gas over separate calls to withdraw + claim
function withdraw(uint256 _amount, bool _claimRewards)
external
override
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
return __withdraw(msg.sender, msg.sender, _amount, _claimRewards);
}
/// @notice Withdraws staked tokens, returning tokens to a specified account,
/// and optionally claims rewards to the staked token holder
/// @param _to The account to receive tokens
/// @param _amount The amount of tokens to withdraw
function withdrawTo(
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external override {
__withdraw(msg.sender, _to, _amount, _claimRewardsToHolder);
}
/// @notice Withdraws staked tokens on behalf of AccountA, returning tokens to a specified AccountB,
/// and optionally claims rewards to the staked token holder
/// @param _onBehalf The account on behalf to withdraw
/// @param _to The account to receive tokens
/// @param _amount The amount of tokens to withdraw
/// @dev The caller must have an adequate ERC20.allowance() for _onBehalf
function withdrawToOnBehalf(
address _onBehalf,
address _to,
uint256 _amount,
bool _claimRewardsToHolder
) external override {
// Validate and reduce sender approval
_approve(_onBehalf, msg.sender, allowance(_onBehalf, msg.sender).sub(_amount));
__withdraw(_onBehalf, _to, _amount, _claimRewardsToHolder);
}
/// @dev Helper to withdraw staked tokens
function __withdraw(
address _from,
address _to,
uint256 _amount,
bool _claimRewards
)
private
nonReentrant
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
// Checkpoint before burning
if (_claimRewards) {
(rewardTokens_, claimedAmounts_) = __checkpointAndClaim(_from);
} else {
__checkpoint([_from, address(0)]);
}
_burn(_from, _amount);
__withdrawLogic(_to, _amount);
emit Withdrawn(msg.sender, _from, _to, _amount);
return (rewardTokens_, claimedAmounts_);
}
/////////////
// REWARDS //
/////////////
// Rewards tokens are added by the inheriting contract. Rewards tokens should be added, but not removed.
// If new rewards tokens need to be added over time, that logic must be handled by the inheriting contract,
// and can make use of __harvestRewardsLogic() if necessary
// INTERNAL FUNCTIONS
/// @dev Helper to add new reward tokens. Silently ignores duplicates.
function __addRewardToken(address _rewardToken) internal {
if (!rewardTokens.contains(_rewardToken)) {
rewardTokens.push(_rewardToken);
emit RewardTokenAdded(_rewardToken);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to calculate an unaccounted for reward amount due to a user based on integral values
function __calcClaimableRewardForIntegralDiff(
address _account,
uint256 _totalHarvestIntegral,
uint256 _userHarvestIntegral
) private view returns (uint256 claimableReward_) {
return
balanceOf(_account).mul(_totalHarvestIntegral.sub(_userHarvestIntegral)).div(
INTEGRAL_PRECISION
);
}
/// @dev Helper to calculate an unaccounted for integral amount based on checkpoint balance diff
function __calcIntegralForBalDiff(
uint256 _supply,
uint256 _currentBalance,
uint256 _lastCheckpointBalance
) private pure returns (uint256 integral_) {
if (_supply > 0) {
uint256 balDiff = _currentBalance.sub(_lastCheckpointBalance);
if (balDiff > 0) {
return balDiff.mul(INTEGRAL_PRECISION).div(_supply);
}
}
return 0;
}
/// @dev Helper to checkpoint harvest data for specified accounts.
/// Harvests all rewards prior to checkpoint.
function __checkpoint(address[2] memory _accounts) private {
// If paused, continue to checkpoint, but don't attempt to get new rewards
if (!isPaused()) {
__harvestRewardsLogic();
}
uint256 supply = totalSupply();
uint256 rewardTokensLength = rewardTokens.length;
for (uint256 i; i < rewardTokensLength; i++) {
__updateHarvest(rewardTokens[i], _accounts, supply);
}
}
/// @dev Helper to checkpoint harvest data for specified accounts.
/// Harvests all rewards prior to checkpoint.
function __checkpointAndClaim(address _account)
private
returns (address[] memory rewardTokens_, uint256[] memory claimedAmounts_)
{
// If paused, continue to checkpoint, but don't attempt to get new rewards
if (!isPaused()) {
__harvestRewardsLogic();
}
uint256 supply = totalSupply();
rewardTokens_ = rewardTokens;
claimedAmounts_ = new uint256[](rewardTokens_.length);
for (uint256 i; i < rewardTokens_.length; i++) {
claimedAmounts_[i] = __updateHarvestAndClaim(rewardTokens_[i], _account, supply);
}
emit RewardsClaimed(msg.sender, _account, rewardTokens_, claimedAmounts_);
return (rewardTokens_, claimedAmounts_);
}
/// @dev Helper to update harvest data
function __updateHarvest(
address _rewardToken,
address[2] memory _accounts,
uint256 _supply
) private {
TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken];
uint256 totalIntegral = totalHarvestData.integral;
uint256 bal = ERC20(_rewardToken).balanceOf(address(this));
uint256 integralToAdd = __calcIntegralForBalDiff(
_supply,
bal,
totalHarvestData.lastCheckpointBalance
);
if (integralToAdd > 0) {
totalIntegral = totalIntegral.add(integralToAdd);
totalHarvestData.integral = uint128(totalIntegral);
emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral);
totalHarvestData.lastCheckpointBalance = uint128(bal);
emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, bal);
}
for (uint256 i; i < _accounts.length; i++) {
// skip address(0), passed in upon mint and burn
if (_accounts[i] == address(0)) continue;
UserHarvestData storage userHarvestData
= rewardTokenToUserToHarvestData[_rewardToken][_accounts[i]];
uint256 userIntegral = userHarvestData.integral;
if (userIntegral < totalIntegral) {
uint256 claimableReward = uint256(userHarvestData.claimableReward).add(
__calcClaimableRewardForIntegralDiff(_accounts[i], totalIntegral, userIntegral)
);
userHarvestData.claimableReward = uint128(claimableReward);
userHarvestData.integral = uint128(totalIntegral);
emit UserHarvestUpdated(
_accounts[i],
_rewardToken,
totalIntegral,
claimableReward
);
}
}
}
/// @dev Helper to update harvest data and claim all rewards to holder
function __updateHarvestAndClaim(
address _rewardToken,
address _account,
uint256 _supply
) private returns (uint256 claimedAmount_) {
TotalHarvestData storage totalHarvestData = rewardTokenToTotalHarvestData[_rewardToken];
uint256 totalIntegral = totalHarvestData.integral;
uint256 integralToAdd = __calcIntegralForBalDiff(
_supply,
ERC20(_rewardToken).balanceOf(address(this)),
totalHarvestData.lastCheckpointBalance
);
if (integralToAdd > 0) {
totalIntegral = totalIntegral.add(integralToAdd);
totalHarvestData.integral = uint128(totalIntegral);
emit TotalHarvestIntegralUpdated(_rewardToken, totalIntegral);
}
UserHarvestData storage userHarvestData
= rewardTokenToUserToHarvestData[_rewardToken][_account];
uint256 userIntegral = userHarvestData.integral;
claimedAmount_ = userHarvestData.claimableReward;
if (userIntegral < totalIntegral) {
userHarvestData.integral = uint128(totalIntegral);
claimedAmount_ = claimedAmount_.add(
__calcClaimableRewardForIntegralDiff(_account, totalIntegral, userIntegral)
);
emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, claimedAmount_);
}
if (claimedAmount_ > 0) {
userHarvestData.claimableReward = 0;
ERC20(_rewardToken).safeTransfer(_account, claimedAmount_);
emit UserHarvestUpdated(_account, _rewardToken, totalIntegral, 0);
}
// Repeat balance lookup since the reward token could have irregular transfer behavior
uint256 finalBal = ERC20(_rewardToken).balanceOf(address(this));
if (finalBal < totalHarvestData.lastCheckpointBalance) {
totalHarvestData.lastCheckpointBalance = uint128(finalBal);
emit TotalHarvestLastCheckpointBalanceUpdated(_rewardToken, finalBal);
}
return claimedAmount_;
}
////////////////////////////////
// REQUIRED VIRTUAL FUNCTIONS //
////////////////////////////////
/// @dev Logic to be run during a deposit, specific to the integrated protocol.
/// Do not mint staking tokens, which already happens during __deposit().
function __depositLogic(address _onBehalf, uint256 _amount) internal virtual;
/// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol.
/// Can also be used to add new rewards tokens dynamically.
/// Do not checkpoint, only harvest the rewards.
function __harvestRewardsLogic() internal virtual;
/// @dev Logic to be run during a withdrawal, specific to the integrated protocol.
/// Do not burn staking tokens, which already happens during __withdraw().
function __withdrawLogic(address _to, uint256 _amount) internal virtual;
/////////////////////
// ERC20 OVERRIDES //
/////////////////////
/// @notice Gets the token decimals
/// @return decimals_ The token decimals
/// @dev Implementing contracts should override to set different decimals
function decimals() public view virtual override returns (uint8 decimals_) {
return DEFAULT_DECIMALS;
}
/// @dev Overrides ERC20._transfer() in order to checkpoint sender and recipient pre-transfer rewards
function _transfer(
address _from,
address _to,
uint256 _amount
) internal override nonReentrant {
__checkpoint([_from, _to]);
super._transfer(_from, _to, _amount);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the reward token at a particular index
/// @return rewardToken_ The reward token address
function getRewardTokenAtIndex(uint256 _index)
public
view
override
returns (address rewardToken_)
{
return rewardTokens[_index];
}
/// @notice Gets the count of reward tokens being harvested
/// @return count_ The count
function getRewardTokenCount() public view override returns (uint256 count_) {
return rewardTokens.length;
}
/// @notice Gets all reward tokens being harvested
/// @return rewardTokens_ The reward tokens
function getRewardTokens() public view override returns (address[] memory rewardTokens_) {
return rewardTokens;
}
/// @notice Gets the TotalHarvestData for a specified reward token
/// @param _rewardToken The reward token
/// @return totalHarvestData_ The TotalHarvestData
function getTotalHarvestDataForRewardToken(address _rewardToken)
public
view
override
returns (TotalHarvestData memory totalHarvestData_)
{
return rewardTokenToTotalHarvestData[_rewardToken];
}
/// @notice Gets the UserHarvestData for a specified account and reward token
/// @param _user The account
/// @param _rewardToken The reward token
/// @return userHarvestData_ The UserHarvestData
function getUserHarvestDataForRewardToken(address _user, address _rewardToken)
public
view
override
returns (UserHarvestData memory userHarvestData_)
{
return rewardTokenToUserToHarvestData[_rewardToken][_user];
}
/// @notice Checks if deposits and new reward harvesting are paused
/// @return isPaused_ True if paused
function isPaused() public view override returns (bool isPaused_) {
return paused;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./StakingWrapperBase.sol";
/// @title StakingWrapperLibBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A staking wrapper base for proxy targets, extending StakingWrapperBase
abstract contract StakingWrapperLibBase is StakingWrapperBase {
event TokenNameSet(string name);
event TokenSymbolSet(string symbol);
string private tokenName;
string private tokenSymbol;
/// @dev Helper function to set token name
function __setTokenName(string memory _name) internal {
tokenName = _name;
emit TokenNameSet(_name);
}
/// @dev Helper function to set token symbol
function __setTokenSymbol(string memory _symbol) internal {
tokenSymbol = _symbol;
emit TokenSymbolSet(_symbol);
}
/////////////////////
// ERC20 OVERRIDES //
/////////////////////
/// @notice Gets the token name
/// @return name_ The token name
/// @dev Overrides the constructor-set storage for use in proxies
function name() public view override returns (string memory name_) {
return tokenName;
}
/// @notice Gets the token symbol
/// @return symbol_ The token symbol
/// @dev Overrides the constructor-set storage for use in proxies
function symbol() public view override returns (string memory symbol_) {
return tokenSymbol;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../utils/beacon-proxy/BeaconProxyFactory.sol";
import "./ConvexCurveLpStakingWrapperLib.sol";
/// @title ConvexCurveLpStakingWrapperFactory Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract factory for ConvexCurveLpStakingWrapper instances
contract ConvexCurveLpStakingWrapperFactory is BeaconProxyFactory {
event WrapperDeployed(uint256 indexed pid, address wrapperProxy, address curveLpToken);
IDispatcher private immutable DISPATCHER_CONTRACT;
mapping(uint256 => address) private pidToWrapper;
// Handy cache for interacting contracts
mapping(address => address) private wrapperToCurveLpToken;
modifier onlyOwner {
require(msg.sender == getOwner(), "Only the owner can call this function");
_;
}
constructor(
address _dispatcher,
address _convexBooster,
address _crvToken,
address _cvxToken
) public BeaconProxyFactory(address(0)) {
DISPATCHER_CONTRACT = IDispatcher(_dispatcher);
__setCanonicalLib(
address(
new ConvexCurveLpStakingWrapperLib(
address(this),
_convexBooster,
_crvToken,
_cvxToken
)
)
);
}
/// @notice Deploys a staking wrapper for a given Convex pool
/// @param _pid The Convex Curve pool id
/// @return wrapperProxy_ The staking wrapper proxy contract address
function deploy(uint256 _pid) external returns (address wrapperProxy_) {
require(getWrapperForConvexPool(_pid) == address(0), "deploy: Wrapper already exists");
bytes memory constructData = abi.encodeWithSelector(
ConvexCurveLpStakingWrapperLib.init.selector,
_pid
);
wrapperProxy_ = deployProxy(constructData);
pidToWrapper[_pid] = wrapperProxy_;
address lpToken = ConvexCurveLpStakingWrapperLib(wrapperProxy_).getCurveLpToken();
wrapperToCurveLpToken[wrapperProxy_] = lpToken;
emit WrapperDeployed(_pid, wrapperProxy_, lpToken);
return wrapperProxy_;
}
/// @notice Pause deposits and harvesting new rewards for the given wrappers
/// @param _wrappers The wrappers to pause
function pauseWrappers(address[] calldata _wrappers) external onlyOwner {
for (uint256 i; i < _wrappers.length; i++) {
ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(true);
}
}
/// @notice Unpauses deposits and harvesting new rewards for the given wrappers
/// @param _wrappers The wrappers to unpause
function unpauseWrappers(address[] calldata _wrappers) external onlyOwner {
for (uint256 i; i < _wrappers.length; i++) {
ConvexCurveLpStakingWrapperLib(_wrappers[i]).togglePause(false);
}
}
////////////////////////////////////
// BEACON PROXY FACTORY OVERRIDES //
////////////////////////////////////
/// @notice Gets the contract owner
/// @return owner_ The contract owner
function getOwner() public view override returns (address owner_) {
return DISPATCHER_CONTRACT.getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
// EXTERNAL FUNCTIONS
/// @notice Gets the Curve LP token address for a given wrapper
/// @param _wrapper The wrapper proxy address
/// @return lpToken_ The Curve LP token address
function getCurveLpTokenForWrapper(address _wrapper) external view returns (address lpToken_) {
return wrapperToCurveLpToken[_wrapper];
}
// PUBLIC FUNCTIONS
/// @notice Gets the wrapper address for a given Convex pool
/// @param _pid The Convex pool id
/// @return wrapper_ The wrapper proxy address
function getWrapperForConvexPool(uint256 _pid) public view returns (address wrapper_) {
return pidToWrapper[_pid];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../../interfaces/IConvexBaseRewardPool.sol";
import "../../../interfaces/IConvexBooster.sol";
import "../../../interfaces/IConvexVirtualBalanceRewardPool.sol";
import "../StakingWrapperLibBase.sol";
/// @title ConvexCurveLpStakingWrapperLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A library contract for ConvexCurveLpStakingWrapper instances
contract ConvexCurveLpStakingWrapperLib is StakingWrapperLibBase {
IConvexBooster private immutable CONVEX_BOOSTER_CONTRACT;
address private immutable CRV_TOKEN;
address private immutable CVX_TOKEN;
address private convexPool;
uint256 private convexPoolId;
address private curveLPToken;
constructor(
address _owner,
address _convexBooster,
address _crvToken,
address _cvxToken
) public StakingWrapperBase(_owner, "", "") {
CONVEX_BOOSTER_CONTRACT = IConvexBooster(_convexBooster);
CRV_TOKEN = _crvToken;
CVX_TOKEN = _cvxToken;
}
/// @notice Initializes the proxy
/// @param _pid The Convex pool id for which to use the proxy
function init(uint256 _pid) external {
// Can validate with any variable set here
require(getCurveLpToken() == address(0), "init: Initialized");
IConvexBooster.PoolInfo memory poolInfo = CONVEX_BOOSTER_CONTRACT.poolInfo(_pid);
// Set ERC20 info on proxy
__setTokenName(string(abi.encodePacked("Enzyme Staked: ", ERC20(poolInfo.token).name())));
__setTokenSymbol(string(abi.encodePacked("stk", ERC20(poolInfo.token).symbol())));
curveLPToken = poolInfo.lptoken;
convexPool = poolInfo.crvRewards;
convexPoolId = _pid;
__addRewardToken(CRV_TOKEN);
__addRewardToken(CVX_TOKEN);
addExtraRewards();
setApprovals();
}
/// @notice Adds rewards tokens that have not yet been added to the wrapper
/// @dev Anybody can call, in case more pool tokens are added.
/// Is called prior to every new harvest.
function addExtraRewards() public {
IConvexBaseRewardPool convexPoolContract = IConvexBaseRewardPool(getConvexPool());
// Could probably exit early after validating that extraRewardsCount + 2 <= rewardsTokens.length,
// but this protects against a reward token being removed that still needs to be paid out
uint256 extraRewardsCount = convexPoolContract.extraRewardsLength();
for (uint256 i; i < extraRewardsCount; i++) {
// __addRewardToken silently ignores duplicates
__addRewardToken(
IConvexVirtualBalanceRewardPool(convexPoolContract.extraRewards(i)).rewardToken()
);
}
}
/// @notice Sets necessary ERC20 approvals, as-needed
function setApprovals() public {
ERC20(getCurveLpToken()).safeApprove(address(CONVEX_BOOSTER_CONTRACT), type(uint256).max);
}
////////////////////////////////
// STAKING WRAPPER BASE LOGIC //
////////////////////////////////
/// @dev Logic to be run during a deposit, specific to the integrated protocol.
/// Do not mint staking tokens, which already happens during __deposit().
function __depositLogic(address _from, uint256 _amount) internal override {
ERC20(getCurveLpToken()).safeTransferFrom(_from, address(this), _amount);
CONVEX_BOOSTER_CONTRACT.deposit(convexPoolId, _amount, true);
}
/// @dev Logic to be run during a checkpoint to harvest new rewards, specific to the integrated protocol.
/// Can also be used to add new rewards tokens dynamically.
/// Do not checkpoint, only harvest the rewards.
function __harvestRewardsLogic() internal override {
// It's probably overly-cautious to check rewards on every call,
// but even when the pool has 1 extra reward token (most have 0) it only adds ~10-15k gas units,
// so more convenient to always check than to monitor for rewards changes.
addExtraRewards();
IConvexBaseRewardPool(getConvexPool()).getReward();
}
/// @dev Logic to be run during a withdrawal, specific to the integrated protocol.
/// Do not burn staking tokens, which already happens during __withdraw().
function __withdrawLogic(address _to, uint256 _amount) internal override {
IConvexBaseRewardPool(getConvexPool()).withdrawAndUnwrap(_amount, false);
ERC20(getCurveLpToken()).safeTransfer(_to, _amount);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the associated Convex reward pool address
/// @return convexPool_ The reward pool
function getConvexPool() public view returns (address convexPool_) {
return convexPool;
}
/// @notice Gets the associated Convex reward pool id (pid)
/// @return convexPoolId_ The pid
function getConvexPoolId() public view returns (uint256 convexPoolId_) {
return convexPoolId;
}
/// @notice Gets the associated Curve LP token
/// @return curveLPToken_ The Curve LP token
function getCurveLpToken() public view returns (address curveLPToken_) {
return curveLPToken;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IConvexBaseRewardPool Interface
/// @author Enzyme Council <[email protected]>
interface IConvexBaseRewardPool {
function extraRewards(uint256) external view returns (address);
function extraRewardsLength() external view returns (uint256);
function getReward() external returns (bool);
function withdrawAndUnwrap(uint256, bool) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title IConvexBooster Interface
/// @author Enzyme Council <[email protected]>
interface IConvexBooster {
struct PoolInfo {
address lptoken;
address token;
address gauge;
address crvRewards;
address stash;
bool shutdown;
}
function deposit(
uint256,
uint256,
bool
) external returns (bool);
function poolInfo(uint256) external view returns (PoolInfo memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IConvexVirtualBalanceRewardPool Interface
/// @author Enzyme Council <[email protected]>
interface IConvexVirtualBalanceRewardPool {
function rewardToken() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/////////////
// STORAGE //
/////////////
/// @dev Helper to remove an item from a storage array
function removeStorageItem(address[] storage _self, address _itemToRemove)
internal
returns (bool removed_)
{
uint256 itemCount = _self.length;
for (uint256 i; i < itemCount; i++) {
if (_self[i] == _itemToRemove) {
if (i < itemCount - 1) {
_self[i] = _self[itemCount - 1];
}
_self.pop();
removed_ = true;
break;
}
}
return removed_;
}
////////////
// MEMORY //
////////////
/// @dev Helper to add an item to an array. Does not assert uniqueness of the new item.
function addItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
nextArray_ = new address[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
nextArray_[_self.length] = _itemToAdd;
return nextArray_;
}
/// @dev Helper to add an item to an array, only if it is not already in the array.
function addUniqueItem(address[] memory _self, address _itemToAdd)
internal
pure
returns (address[] memory nextArray_)
{
if (contains(_self, _itemToAdd)) {
return _self;
}
return addItem(_self, _itemToAdd);
}
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to merge the unique items of a second array.
/// Does not consider uniqueness of either array, only relative uniqueness.
/// Preserves ordering.
function mergeArray(address[] memory _self, address[] memory _arrayToMerge)
internal
pure
returns (address[] memory nextArray_)
{
uint256 newUniqueItemCount;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
newUniqueItemCount++;
}
}
if (newUniqueItemCount == 0) {
return _self;
}
nextArray_ = new address[](_self.length + newUniqueItemCount);
for (uint256 i; i < _self.length; i++) {
nextArray_[i] = _self[i];
}
uint256 nextArrayIndex = _self.length;
for (uint256 i; i < _arrayToMerge.length; i++) {
if (!contains(_self, _arrayToMerge[i])) {
nextArray_[nextArrayIndex] = _arrayToMerge[i];
nextArrayIndex++;
}
}
return nextArray_;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IBeacon.sol";
/// @title BeaconProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract that uses the beacon pattern for instant upgrades
contract BeaconProxy {
address private immutable BEACON;
constructor(bytes memory _constructData, address _beacon) public {
BEACON = _beacon;
(bool success, bytes memory returnData) = IBeacon(_beacon).getCanonicalLib().delegatecall(
_constructData
);
require(success, string(returnData));
}
// solhint-disable-next-line no-complex-fallback
fallback() external payable {
address contractLogic = IBeacon(BEACON).getCanonicalLib();
assembly {
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
receive() external payable {}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./BeaconProxy.sol";
import "./IBeaconProxyFactory.sol";
/// @title BeaconProxyFactory Contract
/// @author Enzyme Council <[email protected]>
/// @notice Factory contract that deploys beacon proxies
abstract contract BeaconProxyFactory is IBeaconProxyFactory {
event CanonicalLibSet(address nextCanonicalLib);
event ProxyDeployed(address indexed caller, address proxy, bytes constructData);
address private canonicalLib;
constructor(address _canonicalLib) public {
__setCanonicalLib(_canonicalLib);
}
/// @notice Deploys a new proxy instance
/// @param _constructData The constructor data with which to call `init()` on the deployed proxy
/// @return proxy_ The proxy address
function deployProxy(bytes memory _constructData) public override returns (address proxy_) {
proxy_ = address(new BeaconProxy(_constructData, address(this)));
emit ProxyDeployed(msg.sender, proxy_, _constructData);
return proxy_;
}
/// @notice Gets the canonical lib used by all proxies
/// @return canonicalLib_ The canonical lib
function getCanonicalLib() public view override returns (address canonicalLib_) {
return canonicalLib;
}
/// @notice Gets the contract owner
/// @return owner_ The contract owner
function getOwner() public view virtual returns (address owner_);
/// @notice Sets the next canonical lib used by all proxies
/// @param _nextCanonicalLib The next canonical lib
function setCanonicalLib(address _nextCanonicalLib) public override {
require(
msg.sender == getOwner(),
"setCanonicalLib: Only the owner can call this function"
);
__setCanonicalLib(_nextCanonicalLib);
}
/// @dev Helper to set the next canonical lib
function __setCanonicalLib(address _nextCanonicalLib) internal {
canonicalLib = _nextCanonicalLib;
emit CanonicalLibSet(_nextCanonicalLib);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IBeacon interface
/// @author Enzyme Council <[email protected]>
interface IBeacon {
function getCanonicalLib() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
import "./IBeacon.sol";
pragma solidity 0.6.12;
/// @title IBeaconProxyFactory interface
/// @author Enzyme Council <[email protected]>
interface IBeaconProxyFactory is IBeacon {
function deployProxy(bytes memory _constructData) external returns (address proxy_);
function setCanonicalLib(address _canonicalLib) external;
} | @notice Converts a given amount of a derivative to its underlying asset values @param _derivative The derivative to convert @param _derivativeAmount The amount of the derivative to convert @return underlyings_ The underlying assets for the _derivative @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount | function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
underlyings_ = new address[](1);
underlyings_[0] = WRAPPER_FACTORY.getCurveLpTokenForWrapper(_derivative);
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount;
return (underlyings_, underlyingAmounts_);
}
| 6,114,835 | [
1,
5692,
279,
864,
3844,
434,
279,
16417,
358,
2097,
6808,
3310,
924,
225,
389,
20615,
1535,
1021,
16417,
358,
1765,
225,
389,
20615,
1535,
6275,
1021,
3844,
434,
326,
16417,
358,
1765,
327,
3613,
715,
899,
67,
1021,
6808,
7176,
364,
326,
389,
20615,
1535,
327,
6808,
6275,
87,
67,
1021,
3844,
434,
1517,
6808,
3310,
364,
326,
7680,
16417,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
7029,
14655,
6291,
1972,
12,
2867,
389,
20615,
1535,
16,
2254,
5034,
389,
20615,
1535,
6275,
13,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
1135,
261,
2867,
8526,
3778,
3613,
715,
899,
67,
16,
2254,
5034,
8526,
3778,
6808,
6275,
87,
67,
13,
203,
565,
288,
203,
3639,
3613,
715,
899,
67,
273,
394,
1758,
8526,
12,
21,
1769,
203,
3639,
3613,
715,
899,
67,
63,
20,
65,
273,
12984,
2203,
3194,
67,
16193,
18,
588,
9423,
48,
84,
1345,
1290,
3611,
24899,
20615,
1535,
1769,
203,
203,
3639,
6808,
6275,
87,
67,
273,
394,
2254,
5034,
8526,
12,
21,
1769,
203,
3639,
6808,
6275,
87,
67,
63,
20,
65,
273,
389,
20615,
1535,
6275,
31,
203,
203,
3639,
327,
261,
9341,
715,
899,
67,
16,
6808,
6275,
87,
67,
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
] |
// solhint-disable
// Imported from https://github.com/UMAprotocol/protocol/blob/4d1c8cc47a4df5e79f978cb05647a7432e111a3d/packages/core/contracts/common/implementation/FixedPoint.sol
pragma solidity 0.6.12;
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SignedSafeMath.sol";
/**
* @title Library for fixed point arithmetic on uints
*/
library FixedPoint {
using SafeMath for uint256;
using SignedSafeMath for int256;
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For unsigned values:
// This can represent a value up to (2^256 - 1)/10^18 = ~10^59. 10^59 will be stored internally as uint256 10^77.
uint256 private constant FP_SCALING_FACTOR = 10**18;
// --------------------------------------- UNSIGNED -----------------------------------------------------------------------------
struct Unsigned {
uint256 rawValue;
}
/**
* @notice Constructs an `Unsigned` from an unscaled uint, e.g., `b=5` gets stored internally as `5**18`.
* @param a uint to convert into a FixedPoint.
* @return the converted FixedPoint.
*/
function fromUnscaledUint(uint256 a) internal pure returns (Unsigned memory) {
return Unsigned(a.mul(FP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if equal, or False.
*/
function isEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a > b`, or False.
*/
function isGreaterThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a < b`, or False.
*/
function isLessThan(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a < b`, or False.
*/
function isLessThan(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, Unsigned memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.
* @param b a uint256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Unsigned memory a, uint256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledUint(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a uint256.
* @param b a FixedPoint.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(uint256 a, Unsigned memory b) internal pure returns (bool) {
return fromUnscaledUint(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the minimum of `a` and `b`.
*/
function min(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the maximum of `a` and `b`.
*/
function max(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Unsigned` to an unscaled uint, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the sum of `a` and `b`.
*/
function add(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return add(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts two `Unsigned`s, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled uint256 from an `Unsigned`, reverting on overflow.
* @param a a FixedPoint.
* @param b a uint256.
* @return the difference of `a` and `b`.
*/
function sub(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return sub(a, fromUnscaledUint(b));
}
/**
* @notice Subtracts an `Unsigned` from an unscaled uint256, reverting on overflow.
* @param a a uint256.
* @param b a FixedPoint.
* @return the difference of `a` and `b`.
*/
function sub(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return sub(fromUnscaledUint(a), b);
}
/**
* @notice Multiplies two `Unsigned`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as a uint256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because FP_SCALING_FACTOR != 0.
return Unsigned(a.rawValue.mul(b.rawValue) / FP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.
* @param b a uint256.
* @return the product of `a` and `b`.
*/
function mul(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Unsigned`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 mulRaw = a.rawValue.mul(b.rawValue);
uint256 mulFloor = mulRaw / FP_SCALING_FACTOR;
uint256 mod = mulRaw.mod(FP_SCALING_FACTOR);
if (mod != 0) {
return Unsigned(mulFloor.add(1));
} else {
return Unsigned(mulFloor);
}
}
/**
* @notice Multiplies an `Unsigned` and an unscaled uint256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.
* @param b a FixedPoint.
* @return the product of `a` and `b`.
*/
function mulCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Unsigned(a.rawValue.mul(b));
}
/**
* @notice Divides one `Unsigned` by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as a uint256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Unsigned(a.rawValue.mul(FP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
return Unsigned(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled uint256 by an `Unsigned`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a uint256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(uint256 a, Unsigned memory b) internal pure returns (Unsigned memory) {
return div(fromUnscaledUint(a), b);
}
/**
* @notice Divides one `Unsigned` by an `Unsigned` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, Unsigned memory b) internal pure returns (Unsigned memory) {
uint256 aScaled = a.rawValue.mul(FP_SCALING_FACTOR);
uint256 divFloor = aScaled.div(b.rawValue);
uint256 mod = aScaled.mod(b.rawValue);
if (mod != 0) {
return Unsigned(divFloor.add(1));
} else {
return Unsigned(divFloor);
}
}
/**
* @notice Divides one `Unsigned` by an unscaled uint256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divCeil(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Unsigned(a.rawValue.div(b))"
// similarly to mulCeil with a uint256 as the second parameter. Therefore we need to convert b into an Unsigned.
// This creates the possibility of overflow if b is very large.
return divCeil(a, fromUnscaledUint(b));
}
/**
* @notice Raises an `Unsigned` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint numerator.
* @param b a uint256 denominator.
* @return output is `a` to the power of `b`.
*/
function pow(Unsigned memory a, uint256 b) internal pure returns (Unsigned memory output) {
output = fromUnscaledUint(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
// ------------------------------------------------- SIGNED -------------------------------------------------------------
// Supports 18 decimals. E.g., 1e18 represents "1", 5e17 represents "0.5".
// For signed values:
// This can represent a value up (or down) to +-(2^255 - 1)/10^18 = ~10^58. 10^58 will be stored internally as int256 10^76.
int256 private constant SFP_SCALING_FACTOR = 10**18;
struct Signed {
int256 rawValue;
}
function fromSigned(Signed memory a) internal pure returns (Unsigned memory) {
require(a.rawValue >= 0, "Negative value provided");
return Unsigned(uint256(a.rawValue));
}
function fromUnsigned(Unsigned memory a) internal pure returns (Signed memory) {
require(a.rawValue <= uint256(type(int256).max), "Unsigned too large");
return Signed(int256(a.rawValue));
}
/**
* @notice Constructs a `Signed` from an unscaled int, e.g., `b=5` gets stored internally as `5**18`.
* @param a int to convert into a FixedPoint.Signed.
* @return the converted FixedPoint.Signed.
*/
function fromUnscaledInt(int256 a) internal pure returns (Signed memory) {
return Signed(a.mul(SFP_SCALING_FACTOR));
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a int256.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue == fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if equal, or False.
*/
function isEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue == b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a > b`, or False.
*/
function isGreaterThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue > fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a > b`, or False.
*/
function isGreaterThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue > b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue >= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is greater than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a >= b`, or False.
*/
function isGreaterThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue >= b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a < b`, or False.
*/
function isLessThan(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue < fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a < b`, or False.
*/
function isLessThan(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue < b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, Signed memory b) internal pure returns (bool) {
return a.rawValue <= b.rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(Signed memory a, int256 b) internal pure returns (bool) {
return a.rawValue <= fromUnscaledInt(b).rawValue;
}
/**
* @notice Whether `a` is less than or equal to `b`.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return True if `a <= b`, or False.
*/
function isLessThanOrEqual(int256 a, Signed memory b) internal pure returns (bool) {
return fromUnscaledInt(a).rawValue <= b.rawValue;
}
/**
* @notice The minimum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the minimum of `a` and `b`.
*/
function min(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue < b.rawValue ? a : b;
}
/**
* @notice The maximum of `a` and `b`.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the maximum of `a` and `b`.
*/
function max(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return a.rawValue > b.rawValue ? a : b;
}
/**
* @notice Adds two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.add(b.rawValue));
}
/**
* @notice Adds an `Signed` to an unscaled int, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the sum of `a` and `b`.
*/
function add(Signed memory a, int256 b) internal pure returns (Signed memory) {
return add(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts two `Signed`s, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
return Signed(a.rawValue.sub(b.rawValue));
}
/**
* @notice Subtracts an unscaled int256 from an `Signed`, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the difference of `a` and `b`.
*/
function sub(Signed memory a, int256 b) internal pure returns (Signed memory) {
return sub(a, fromUnscaledInt(b));
}
/**
* @notice Subtracts an `Signed` from an unscaled int256, reverting on overflow.
* @param a an int256.
* @param b a FixedPoint.Signed.
* @return the difference of `a` and `b`.
*/
function sub(int256 a, Signed memory b) internal pure returns (Signed memory) {
return sub(fromUnscaledInt(a), b);
}
/**
* @notice Multiplies two `Signed`s, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max output for the represented number is ~10^41, otherwise an intermediate value overflows. 10^41 is
// stored internally as an int256 ~10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 1.4 * 2e-18 = 2.8e-18, which
// would round to 3, but this computation produces the result 2.
// No need to use SafeMath because SFP_SCALING_FACTOR != 0.
return Signed(a.rawValue.mul(b.rawValue) / SFP_SCALING_FACTOR);
}
/**
* @notice Multiplies an `Signed` and an unscaled int256, reverting on overflow.
* @dev This will "floor" the product.
* @param a a FixedPoint.Signed.
* @param b an int256.
* @return the product of `a` and `b`.
*/
function mul(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.mul(b));
}
/**
* @notice Multiplies two `Signed`s and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 mulRaw = a.rawValue.mul(b.rawValue);
int256 mulTowardsZero = mulRaw / SFP_SCALING_FACTOR;
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = mulRaw % SFP_SCALING_FACTOR;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(mulTowardsZero.add(valueToAdd));
} else {
return Signed(mulTowardsZero);
}
}
/**
* @notice Multiplies an `Signed` and an unscaled int256 and "ceil's" the product, reverting on overflow.
* @param a a FixedPoint.Signed.
* @param b a FixedPoint.Signed.
* @return the product of `a` and `b`.
*/
function mulAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Since b is an int, there is no risk of truncation and we can just mul it normally
return Signed(a.rawValue.mul(b));
}
/**
* @notice Divides one `Signed` by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
// There are two caveats with this computation:
// 1. Max value for the number dividend `a` represents is ~10^41, otherwise an intermediate value overflows.
// 10^41 is stored internally as an int256 10^59.
// 2. Results that can't be represented exactly are truncated not rounded. E.g., 2 / 3 = 0.6 repeating, which
// would round to 0.666666666666666667, but this computation produces the result 0.666666666666666666.
return Signed(a.rawValue.mul(SFP_SCALING_FACTOR).div(b.rawValue));
}
/**
* @notice Divides one `Signed` by an unscaled int256, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(Signed memory a, int256 b) internal pure returns (Signed memory) {
return Signed(a.rawValue.div(b));
}
/**
* @notice Divides one unscaled int256 by an `Signed`, reverting on overflow or division by 0.
* @dev This will "floor" the quotient.
* @param a an int256 numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function div(int256 a, Signed memory b) internal pure returns (Signed memory) {
return div(fromUnscaledInt(a), b);
}
/**
* @notice Divides one `Signed` by an `Signed` and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b a FixedPoint denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, Signed memory b) internal pure returns (Signed memory) {
int256 aScaled = a.rawValue.mul(SFP_SCALING_FACTOR);
int256 divTowardsZero = aScaled.div(b.rawValue);
// Manual mod because SignedSafeMath doesn't support it.
int256 mod = aScaled % b.rawValue;
if (mod != 0) {
bool isResultPositive = isLessThan(a, 0) == isLessThan(b, 0);
int256 valueToAdd = isResultPositive ? int256(1) : int256(-1);
return Signed(divTowardsZero.add(valueToAdd));
} else {
return Signed(divTowardsZero);
}
}
/**
* @notice Divides one `Signed` by an unscaled int256 and "ceil's" the quotient, reverting on overflow or division by 0.
* @param a a FixedPoint numerator.
* @param b an int256 denominator.
* @return the quotient of `a` divided by `b`.
*/
function divAwayFromZero(Signed memory a, int256 b) internal pure returns (Signed memory) {
// Because it is possible that a quotient gets truncated, we can't just call "Signed(a.rawValue.div(b))"
// similarly to mulCeil with an int256 as the second parameter. Therefore we need to convert b into an Signed.
// This creates the possibility of overflow if b is very large.
return divAwayFromZero(a, fromUnscaledInt(b));
}
/**
* @notice Raises an `Signed` to the power of an unscaled uint256, reverting on overflow. E.g., `b=2` squares `a`.
* @dev This will "floor" the result.
* @param a a FixedPoint.Signed.
* @param b a uint256 (negative exponents are not allowed).
* @return output is `a` to the power of `b`.
*/
function pow(Signed memory a, uint256 b) internal pure returns (Signed memory output) {
output = fromUnscaledInt(1);
for (uint256 i = 0; i < b; i = i.add(1)) {
output = mul(output, a);
}
}
}
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.6.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Integer division of two signed integers truncating the quotient, reverts on division by zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./CreditLine.sol";
import "../external/FixedPoint.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
/**
* @title The Accountant
* @notice Library for handling key financial calculations, such as interest and principal accrual.
* @author Goldfinch
*/
library Accountant {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Signed;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for int256;
using FixedPoint for uint256;
// Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled
uint256 public constant FP_SCALING_FACTOR = 10**18;
uint256 public constant INTEREST_DECIMALS = 1e8;
uint256 public constant BLOCKS_PER_DAY = 5760;
uint256 public constant BLOCKS_PER_YEAR = (BLOCKS_PER_DAY * 365);
struct PaymentAllocation {
uint256 interestPayment;
uint256 principalPayment;
uint256 additionalBalancePayment;
}
function calculateInterestAndPrincipalAccrued(
CreditLine cl,
uint256 blockNumber,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
uint256 interestAccrued = calculateInterestAccrued(cl, blockNumber, lateFeeGracePeriod);
uint256 principalAccrued = calculatePrincipalAccrued(cl, blockNumber);
return (interestAccrued, principalAccrued);
}
function calculatePrincipalAccrued(CreditLine cl, uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= cl.termEndBlock()) {
return cl.balance();
} else {
return 0;
}
}
function calculateWritedownFor(
CreditLine cl,
uint256 blockNumber,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl);
if (amountOwedPerDay.isEqual(0)) {
return (0, 0);
}
FixedPoint.Unsigned memory fpGracePeriod =
FixedPoint.min(
FixedPoint.fromUnscaledUint(gracePeriodInDays),
FixedPoint.fromUnscaledUint(cl.paymentPeriodInDays())
);
FixedPoint.Unsigned memory daysLate;
// Excel math: =min(1,max(0,periods_late_in_days-graceperiod_in_days)/MAX_ALLOWED_DAYS_LATE) grace_period = 30,
// Before the term end block, we use the interestOwed to calculate the periods late. However, after the loan term
// has ended, since the interest is a much smaller fraction of the principal, we cannot reliably use interest to
// calculate the periods later.
uint256 totalOwed = cl.interestOwed().add(cl.principalOwed());
daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay);
if (blockNumber > cl.termEndBlock()) {
uint256 blocksLate = blockNumber.sub(cl.termEndBlock());
daysLate = daysLate.add(FixedPoint.fromUnscaledUint(blocksLate).div(BLOCKS_PER_DAY));
}
FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate);
FixedPoint.Unsigned memory writedownPercent;
if (daysLate.isLessThanOrEqual(fpGracePeriod)) {
// Within the grace period, we don't have to write down, so assume 0%
writedownPercent = FixedPoint.fromUnscaledUint(0);
} else {
writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate));
}
FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(cl.balance()).div(FP_SCALING_FACTOR);
// This will return a number between 0-100 representing the write down percent with no decimals
uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue;
return (unscaledWritedownPercent, writedownAmount.rawValue);
}
function calculateAmountOwedForOneDay(CreditLine cl) public view returns (FixedPoint.Unsigned memory) {
// Determine theoretical interestOwed for one full day
uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS);
FixedPoint.Unsigned memory interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365);
return interestOwed;
}
function calculateInterestAccrued(
CreditLine cl,
uint256 blockNumber,
uint256 lateFeeGracePeriodInDays
) public view returns (uint256) {
// We use Math.min here to prevent integer overflow (ie. go negative) when calculating
// numBlocksElapsed. Typically this shouldn't be possible, because
// the interestAccruedAsOfBlock couldn't be *after* the current blockNumber. However, when assessing
// we allow this function to be called with a past block number, which raises the possibility
// of overflow.
// This use of min should not generate incorrect interest calculations, since
// this functions purpose is just to normalize balances, and will be called any time
// a balance affecting action takes place (eg. drawdown, repayment, assessment)
uint256 interestAccruedAsOfBlock = Math.min(blockNumber, cl.interestAccruedAsOfBlock());
uint256 numBlocksElapsed = blockNumber.sub(interestAccruedAsOfBlock);
uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS);
uint256 interestOwed = totalInterestPerYear.mul(numBlocksElapsed).div(BLOCKS_PER_YEAR);
if (lateFeeApplicable(cl, blockNumber, lateFeeGracePeriodInDays)) {
uint256 lateFeeInterestPerYear = cl.balance().mul(cl.lateFeeApr()).div(INTEREST_DECIMALS);
uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(numBlocksElapsed).div(BLOCKS_PER_YEAR);
interestOwed = interestOwed.add(additionalLateFeeInterest);
}
return interestOwed;
}
function lateFeeApplicable(
CreditLine cl,
uint256 blockNumber,
uint256 gracePeriodInDays
) public view returns (bool) {
uint256 blocksLate = blockNumber.sub(cl.lastFullPaymentBlock());
gracePeriodInDays = Math.min(gracePeriodInDays, cl.paymentPeriodInDays());
return cl.lateFeeApr() > 0 && blocksLate > gracePeriodInDays.mul(BLOCKS_PER_DAY);
}
function allocatePayment(
uint256 paymentAmount,
uint256 balance,
uint256 interestOwed,
uint256 principalOwed
) public pure returns (PaymentAllocation memory) {
uint256 paymentRemaining = paymentAmount;
uint256 interestPayment = Math.min(interestOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(interestPayment);
uint256 principalPayment = Math.min(principalOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(principalPayment);
uint256 balanceRemaining = balance.sub(principalPayment);
uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining);
return
PaymentAllocation({
interestPayment: interestPayment,
principalPayment: principalPayment,
additionalBalancePayment: additionalBalancePayment
});
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "./BaseUpgradeablePausable.sol";
import "../interfaces/IERC20withDec.sol";
/**
* @title CreditLine
* @notice A "dumb" state container that represents the agreement between an Underwriter and
* the borrower. Includes the terms of the loan, as well as the current accounting state, such as interest owed.
* This contract purposefully has essentially no business logic. Really just setters and getters.
* @author Goldfinch
*/
// solhint-disable-next-line max-states-count
contract CreditLine is BaseUpgradeablePausable {
// Credit line terms
address public borrower;
address public underwriter;
uint256 public limit;
uint256 public interestApr;
uint256 public paymentPeriodInDays;
uint256 public termInDays;
uint256 public lateFeeApr;
// Accounting variables
uint256 public balance;
uint256 public interestOwed;
uint256 public principalOwed;
uint256 public termEndBlock;
uint256 public nextDueBlock;
uint256 public interestAccruedAsOfBlock;
uint256 public writedownAmount;
uint256 public lastFullPaymentBlock;
function initialize(
address owner,
address _borrower,
address _underwriter,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) public initializer {
require(owner != address(0) && _borrower != address(0) && _underwriter != address(0), "Zero address passed in");
__BaseUpgradeablePausable__init(owner);
borrower = _borrower;
underwriter = _underwriter;
limit = _limit;
interestApr = _interestApr;
paymentPeriodInDays = _paymentPeriodInDays;
termInDays = _termInDays;
lateFeeApr = _lateFeeApr;
interestAccruedAsOfBlock = block.number;
}
function setTermEndBlock(uint256 newTermEndBlock) external onlyAdmin {
termEndBlock = newTermEndBlock;
}
function setNextDueBlock(uint256 newNextDueBlock) external onlyAdmin {
nextDueBlock = newNextDueBlock;
}
function setBalance(uint256 newBalance) external onlyAdmin {
balance = newBalance;
}
function setInterestOwed(uint256 newInterestOwed) external onlyAdmin {
interestOwed = newInterestOwed;
}
function setPrincipalOwed(uint256 newPrincipalOwed) external onlyAdmin {
principalOwed = newPrincipalOwed;
}
function setInterestAccruedAsOfBlock(uint256 newInterestAccruedAsOfBlock) external onlyAdmin {
interestAccruedAsOfBlock = newInterestAccruedAsOfBlock;
}
function setWritedownAmount(uint256 newWritedownAmount) external onlyAdmin {
writedownAmount = newWritedownAmount;
}
function setLastFullPaymentBlock(uint256 newLastFullPaymentBlock) external onlyAdmin {
lastFullPaymentBlock = newLastFullPaymentBlock;
}
function setLateFeeApr(uint256 newLateFeeApr) external onlyAdmin {
lateFeeApr = newLateFeeApr;
}
function setLimit(uint256 newAmount) external onlyAdminOrUnderwriter {
limit = newAmount;
}
function authorizePool(address configAddress) external onlyAdmin {
GoldfinchConfig config = GoldfinchConfig(configAddress);
address poolAddress = config.getAddress(uint256(ConfigOptions.Addresses.Pool));
address usdcAddress = config.getAddress(uint256(ConfigOptions.Addresses.USDC));
// Approve the pool for an infinite amount
bool success = IERC20withDec(usdcAddress).approve(poolAddress, uint256(-1));
require(success, "Failed to approve USDC");
}
modifier onlyAdminOrUnderwriter() {
require(isAdmin() || _msgSender() == underwriter, "Restricted to owner or underwriter");
_;
}
}
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./BaseUpgradeablePausable.sol";
import "./ConfigOptions.sol";
/**
* @title GoldfinchConfig
* @notice This contract stores mappings of useful "protocol config state", giving a central place
* for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars
* are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol.
* @author Goldfinch
*/
contract GoldfinchConfig is BaseUpgradeablePausable {
mapping(uint256 => address) public addresses;
mapping(uint256 => uint256) public numbers;
event AddressUpdated(address owner, string name, address oldValue, address newValue);
event NumberUpdated(address owner, string name, uint256 oldValue, uint256 newValue);
function initialize(address owner) public initializer {
__BaseUpgradeablePausable__init(owner);
}
function setAddress(uint256 addressKey, address newAddress) public onlyAdmin {
require(addresses[addressKey] == address(0), "Address has already been initialized");
emit AddressUpdated(msg.sender, ConfigOptions.getAddressName(addressKey), addresses[addressKey], newAddress);
addresses[addressKey] = newAddress;
}
function setNumber(uint256 number, uint256 newNumber) public onlyAdmin {
emit NumberUpdated(msg.sender, ConfigOptions.getNumberName(number), numbers[number], newNumber);
numbers[number] = newNumber;
}
function setCreditLineImplementation(address newCreditLine) public onlyAdmin {
uint256 addressKey = uint256(ConfigOptions.Addresses.CreditLineImplementation);
emit AddressUpdated(msg.sender, ConfigOptions.getAddressName(addressKey), addresses[addressKey], newCreditLine);
addresses[addressKey] = newCreditLine;
}
function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve);
emit AddressUpdated(msg.sender, ConfigOptions.getAddressName(key), addresses[key], newTreasuryReserve);
addresses[key] = newTreasuryReserve;
}
/*
Using custom getters incase we want to change underlying implementation later,
or add checks or validations later on.
*/
function getAddress(uint256 addressKey) public view returns (address) {
// Cheap way to see if it's an invalid number
ConfigOptions.Addresses(addressKey);
return addresses[addressKey];
}
function getNumber(uint256 number) public view returns (uint256) {
// Cheap way to see if it's an invalid number
ConfigOptions.Numbers(number);
return numbers[number];
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./PauserPausable.sol";
/**
* @title BaseUpgradeablePausable contract
* @notice This is our Base contract that most other contracts inherit from. It includes many standard
* useful abilities like ugpradeability, pausability, access control, and re-entrancy guards.
* @author Goldfinch
*/
contract BaseUpgradeablePausable is
Initializable,
AccessControlUpgradeSafe,
PauserPausable,
ReentrancyGuardUpgradeSafe
{
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
using SafeMath for uint256;
// Pre-reserving a few slots in the base contract in case we need to add things in the future.
// This does not actually take up gas cost or storage cost, but it does reserve the storage slots.
// See OpenZeppelin's use of this pattern here:
// https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37
uint256[50] private __gap1;
uint256[50] private __gap2;
uint256[50] private __gap3;
uint256[50] private __gap4;
// solhint-disable-next-line func-name-mixedcase
function __BaseUpgradeablePausable__init(address owner) public initializer {
require(owner != address(0), "Owner cannot be the zero address");
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
/*
Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's.
*/
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20withDec is IERC20 {
/**
* @dev Returns the number of decimals used for the token
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title ConfigOptions
* @notice A central place for enumerating the configurable options of our GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigOptions {
// NEVER EVER CHANGE THE ORDER OF THESE!
// You can rename or append. But NEVER change the order.
enum Numbers {
TransactionLimit,
TotalFundsLimit,
MaxUnderwriterLimit,
ReserveDenominator,
WithdrawFeeDenominator,
LatenessGracePeriodInDays,
LatenessMaxDays
}
enum Addresses {
Pool,
CreditLineImplementation,
CreditLineFactory,
CreditDesk,
Fidu,
USDC,
TreasuryReserve,
ProtocolAdmin
}
function getNumberName(uint256 number) public pure returns (string memory) {
Numbers numberName = Numbers(number);
if (Numbers.TransactionLimit == numberName) {
return "TransactionLimit";
}
if (Numbers.TotalFundsLimit == numberName) {
return "TotalFundsLimit";
}
if (Numbers.MaxUnderwriterLimit == numberName) {
return "MaxUnderwriterLimit";
}
if (Numbers.ReserveDenominator == numberName) {
return "ReserveDenominator";
}
if (Numbers.WithdrawFeeDenominator == numberName) {
return "WithdrawFeeDenominator";
}
if (Numbers.LatenessGracePeriodInDays == numberName) {
return "LatenessGracePeriodInDays";
}
if (Numbers.LatenessMaxDays == numberName) {
return "LatenessMaxDays";
}
revert("Unknown value passed to getNumberName");
}
function getAddressName(uint256 addressKey) public pure returns (string memory) {
Addresses addressName = Addresses(addressKey);
if (Addresses.Pool == addressName) {
return "Pool";
}
if (Addresses.CreditLineImplementation == addressName) {
return "CreditLineImplementation";
}
if (Addresses.CreditLineFactory == addressName) {
return "CreditLineFactory";
}
if (Addresses.CreditDesk == addressName) {
return "CreditDesk";
}
if (Addresses.Fidu == addressName) {
return "Fidu";
}
if (Addresses.USDC == addressName) {
return "USDC";
}
if (Addresses.TreasuryReserve == addressName) {
return "TreasuryReserve";
}
if (Addresses.ProtocolAdmin == addressName) {
return "ProtocolAdmin";
}
revert("Unknown value passed to getAddressName");
}
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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, _msgSender()));
* ...
* }
* ```
*
* 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}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
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.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// Storing an initial 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 percetange 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.
_notEntered = true;
}
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
uint256[49] private __gap;
}
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;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
/**
* @title PauserPausable
* @notice Inheriting from OpenZeppelin's Pausable contract, this does small
* augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract.
* It is meant to be inherited.
* @author Goldfinch
*/
contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// solhint-disable-next-line func-name-mixedcase
function __PauserPausable__init() public initializer {
__Pausable_init_unchained();
}
/**
* @dev Pauses all functions guarded by Pause
*
* See {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the PAUSER_ROLE.
*/
function pause() public onlyPauserRole {
_pause();
}
/**
* @dev Unpauses the contract
*
* See {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the Pauser role
*/
function unpause() public onlyPauserRole {
_unpause();
}
modifier onlyPauserRole() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action");
_;
}
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
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");
}
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
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: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/Accountant.sol";
import "../protocol/CreditLine.sol";
contract TestAccountant {
function calculateInterestAndPrincipalAccrued(
address creditLineAddress,
uint256 blockNumber,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateInterestAndPrincipalAccrued(cl, blockNumber, lateFeeGracePeriod);
}
function calculateWritedownFor(
address creditLineAddress,
uint256 blockNumber,
uint256 gracePeriod,
uint256 maxLatePeriods
) public view returns (uint256, uint256) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateWritedownFor(cl, blockNumber, gracePeriod, maxLatePeriods);
}
function calculateAmountOwedForOneDay(address creditLineAddress) public view returns (FixedPoint.Unsigned memory) {
CreditLine cl = CreditLine(creditLineAddress);
return Accountant.calculateAmountOwedForOneDay(cl);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/math/Math.sol";
import "../protocol/BaseUpgradeablePausable.sol";
import "../protocol/Pool.sol";
import "../protocol/Accountant.sol";
import "../protocol/CreditLine.sol";
import "../protocol/GoldfinchConfig.sol";
contract FakeV2CreditDesk is BaseUpgradeablePausable {
uint256 public totalWritedowns;
uint256 public totalLoansOutstanding;
// Approximate number of blocks
uint256 public constant BLOCKS_PER_DAY = 5760;
GoldfinchConfig public config;
struct Underwriter {
uint256 governanceLimit;
address[] creditLines;
}
struct Borrower {
address[] creditLines;
}
event PaymentMade(
address indexed payer,
address indexed creditLine,
uint256 interestAmount,
uint256 principalAmount,
uint256 remainingAmount
);
event PrepaymentMade(address indexed payer, address indexed creditLine, uint256 prepaymentAmount);
event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount);
event CreditLineCreated(address indexed borrower, address indexed creditLine);
event PoolAddressUpdated(address indexed oldAddress, address indexed newAddress);
event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit);
event LimitChanged(address indexed owner, string limitType, uint256 amount);
mapping(address => Underwriter) public underwriters;
mapping(address => Borrower) private borrowers;
function initialize(address owner, GoldfinchConfig _config) public initializer {
return;
}
function someBrandNewFunction() public pure returns (uint256) {
return 5;
}
function getUnderwriterCreditLines(address underwriterAddress) public view returns (address[] memory) {
return underwriters[underwriterAddress].creditLines;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
/**
* @title Goldfinch's Pool contract
* @notice Main entry point for LP's (a.k.a. capital providers)
* Handles key logic for depositing and withdrawing funds from the Pool
* @author Goldfinch
*/
contract Pool is BaseUpgradeablePausable, IPool {
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
// $1 threshold to handle potential rounding errors, from differing decimals on Fidu and USDC;
uint256 constant ASSET_LIABILITY_MATCH_THRESHOLD = 1e6;
event DepositMade(address indexed capitalProvider, uint256 amount, uint256 shares);
event WithdrawalMade(address indexed capitalProvider, uint256 userAmount, uint256 reserveAmount);
event TransferMade(address indexed from, address indexed to, uint256 amount);
event InterestCollected(address indexed payer, uint256 poolAmount, uint256 reserveAmount);
event PrincipalCollected(address indexed payer, uint256 amount);
event ReserveFundsCollected(address indexed user, uint256 amount);
event PrincipalWrittendown(address indexed creditline, int256 amount);
/**
* @notice Run only once, on initialization
* @param owner The address of who should have the "OWNER_ROLE" of this contract
* @param _config The address of the GoldfinchConfig contract
*/
function initialize(address owner, GoldfinchConfig _config) public initializer {
__BaseUpgradeablePausable__init(owner);
config = _config;
sharePrice = fiduMantissa();
IERC20withDec usdc = config.getUSDC();
// Sanity check the address
usdc.totalSupply();
// Unlock self for infinite amount
bool success = usdc.approve(address(this), uint256(-1));
require(success, "Failed to approve USDC");
}
/**
* @notice Deposits `amount` USDC from msg.sender into the Pool, and returns you the equivalent value of FIDU tokens
* @param amount The amount of USDC to deposit
*/
function deposit(uint256 amount) external override whenNotPaused withinTransactionLimit(amount) nonReentrant {
require(amount > 0, "Must deposit more than zero");
// Check if the amount of new shares to be added is within limits
uint256 depositShares = getNumShares(amount);
uint256 potentialNewTotalShares = totalShares().add(depositShares);
require(poolWithinLimit(potentialNewTotalShares), "Deposit would put the Pool over the total limit.");
emit DepositMade(msg.sender, amount, depositShares);
bool success = doUSDCTransfer(msg.sender, address(this), amount);
require(success, "Failed to transfer for deposit");
config.getFidu().mintTo(msg.sender, depositShares);
assert(assetsMatchLiabilities());
}
/**
* @notice Withdraws `amount` USDC from the Pool to msg.sender, and burns the equivalent value of FIDU tokens
* @param amount The amount of USDC to withdraw
*/
function withdraw(uint256 amount) external override whenNotPaused withinTransactionLimit(amount) nonReentrant {
require(amount > 0, "Must withdraw more than zero");
// Determine current shares the address has and the shares requested to withdraw
uint256 currentShares = config.getFidu().balanceOf(msg.sender);
uint256 withdrawShares = getNumShares(amount);
// Ensure the address has enough value in the pool
require(withdrawShares <= currentShares, "Amount requested is greater than what this address owns");
uint256 reserveAmount = amount.div(config.getWithdrawFeeDenominator());
uint256 userAmount = amount.sub(reserveAmount);
emit WithdrawalMade(msg.sender, userAmount, reserveAmount);
// Send the amounts
bool success = doUSDCTransfer(address(this), msg.sender, userAmount);
require(success, "Failed to transfer for withdraw");
sendToReserve(address(this), reserveAmount, msg.sender);
// Burn the shares
config.getFidu().burnFrom(msg.sender, withdrawShares);
assert(assetsMatchLiabilities());
}
/**
* @notice Collects `amount` USDC in interest from `from` and sends it to the Pool.
* This also increases the share price accordingly. A portion is sent to the Goldfinch Reserve address
* @param from The address to take the USDC from. Implicitly, the Pool
* must be authorized to move USDC on behalf of `from`.
* @param amount the amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function collectInterestRepayment(address from, uint256 amount) external override onlyCreditDesk whenNotPaused {
uint256 reserveAmount = amount.div(config.getReserveDenominator());
uint256 poolAmount = amount.sub(reserveAmount);
emit InterestCollected(from, poolAmount, reserveAmount);
uint256 increment = usdcToSharePrice(poolAmount);
sharePrice = sharePrice.add(increment);
sendToReserve(from, reserveAmount, from);
bool success = doUSDCTransfer(from, address(this), poolAmount);
require(success, "Failed to transfer interest payment");
}
/**
* @notice Collects `amount` USDC in principal from `from` and sends it to the Pool.
* The key difference from `collectInterestPayment` is that this does not change the sharePrice.
* The reason it does not is because the principal is already baked in. ie. we implicitly assume all principal
* will be returned to the Pool. But if borrowers are late with payments, we have a writedown schedule that adjusts
* the sharePrice downwards to reflect the lowered confidence in that borrower.
* @param from The address to take the USDC from. Implicitly, the Pool
* must be authorized to move USDC on behalf of `from`.
* @param amount the amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function collectPrincipalRepayment(address from, uint256 amount) external override onlyCreditDesk whenNotPaused {
// Purposefully does nothing except receive money. No share price updates for principal.
emit PrincipalCollected(from, amount);
bool success = doUSDCTransfer(from, address(this), amount);
require(success, "Failed to principal repayment");
}
function distributeLosses(address creditlineAddress, int256 writedownDelta)
external
override
onlyCreditDesk
whenNotPaused
{
if (writedownDelta > 0) {
uint256 delta = usdcToSharePrice(uint256(writedownDelta));
sharePrice = sharePrice.add(delta);
} else {
// If delta is negative, convert to positive uint, and sub from sharePrice
uint256 delta = usdcToSharePrice(uint256(writedownDelta * -1));
sharePrice = sharePrice.sub(delta);
}
emit PrincipalWrittendown(creditlineAddress, writedownDelta);
}
/**
* @notice Moves `amount` USDC from `from`, to `to`.
* @param from The address to take the USDC from. Implicitly, the Pool
* must be authorized to move USDC on behalf of `from`.
* @param to The address that the USDC should be moved to
* @param amount the amount of USDC to move to the Pool
*
* Requirements:
* - The caller must be the Credit Desk. Not even the owner can call this function.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public override onlyCreditDesk whenNotPaused returns (bool) {
bool result = doUSDCTransfer(from, to, amount);
emit TransferMade(from, to, amount);
return result;
}
function assets() public view override returns (uint256) {
return
config.getUSDC().balanceOf(config.poolAddress()).add(config.getCreditDesk().totalLoansOutstanding()).sub(
config.getCreditDesk().totalWritedowns()
);
}
/* Internal Functions */
function fiduMantissa() internal view returns (uint256) {
return uint256(10)**uint256(config.getFidu().decimals());
}
function usdcMantissa() internal view returns (uint256) {
return uint256(10)**uint256(config.getUSDC().decimals());
}
function usdcToFidu(uint256 amount) internal view returns (uint256) {
return amount.mul(fiduMantissa()).div(usdcMantissa());
}
function totalShares() internal view returns (uint256) {
return config.getFidu().totalSupply();
}
function usdcToSharePrice(uint256 usdcAmount) internal view returns (uint256) {
return usdcToFidu(usdcAmount).mul(fiduMantissa()).div(totalShares());
}
function poolWithinLimit(uint256 _totalShares) internal view returns (bool) {
return
_totalShares.mul(sharePrice).div(fiduMantissa()) <=
usdcToFidu(config.getNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit)));
}
function transactionWithinLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit));
}
function getNumShares(uint256 amount) internal view returns (uint256) {
return usdcToFidu(amount).mul(fiduMantissa()).div(sharePrice);
}
function assetsMatchLiabilities() internal view returns (bool) {
uint256 liabilities = config.getFidu().totalSupply().mul(sharePrice).div(fiduMantissa());
uint256 liabilitiesInDollars = fiduToUSDC(liabilities);
uint256 _assets = assets();
if (_assets >= liabilitiesInDollars) {
return _assets.sub(liabilitiesInDollars) <= ASSET_LIABILITY_MATCH_THRESHOLD;
} else {
return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD;
}
}
function fiduToUSDC(uint256 amount) internal view returns (uint256) {
return amount.div(fiduMantissa().div(usdcMantissa()));
}
function sendToReserve(
address from,
uint256 amount,
address userForEvent
) internal {
emit ReserveFundsCollected(userForEvent, amount);
bool success = doUSDCTransfer(from, config.reserveAddress(), amount);
require(success, "Reserve transfer was not successful");
}
function doUSDCTransfer(
address from,
address to,
uint256 amount
) internal returns (bool) {
require(transactionWithinLimit(amount), "Amount is over the per-transaction limit");
require(to != address(0), "Can't send to zero address");
IERC20withDec usdc = config.getUSDC();
uint256 balanceBefore = usdc.balanceOf(to);
bool success = usdc.transferFrom(from, to, amount);
// Calculate the amount that was *actually* transferred
uint256 balanceAfter = usdc.balanceOf(to);
require(balanceAfter >= balanceBefore, "Token Transfer Overflow Error");
return success;
}
modifier withinTransactionLimit(uint256 amount) {
require(transactionWithinLimit(amount), "Amount is over the per-transaction limit");
_;
}
modifier onlyCreditDesk() {
require(msg.sender == config.creditDeskAddress(), "Only the credit desk is allowed to call this function");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "../interfaces/IPool.sol";
import "../interfaces/IFidu.sol";
import "../interfaces/ICreditDesk.sol";
import "../interfaces/IERC20withDec.sol";
/**
* @title ConfigHelper
* @notice A convenience library for getting easy access to other contracts and constants within the
* protocol, through the use of the GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigHelper {
function getPool(GoldfinchConfig config) internal view returns (IPool) {
return IPool(poolAddress(config));
}
function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) {
return IERC20withDec(config.getAddress(uint256(ConfigOptions.Addresses.USDC)));
}
function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) {
return ICreditDesk(creditDeskAddress(config));
}
function getFidu(GoldfinchConfig config) internal view returns (IFidu) {
return IFidu(fiduAddress(config));
}
function poolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Pool));
}
function creditDeskAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk));
}
function fiduAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Fidu));
}
function reserveAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve));
}
function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin));
}
function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator));
}
function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator));
}
function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays));
}
function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
abstract contract IPool {
uint256 public sharePrice;
function deposit(uint256 amount) external virtual;
function withdraw(uint256 amount) external virtual;
function collectInterestRepayment(address from, uint256 amount) external virtual;
function collectPrincipalRepayment(address from, uint256 amount) external virtual;
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool);
function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual;
function assets() public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IERC20withDec.sol";
interface IFidu is IERC20withDec {
function mintTo(address to, uint256 amount) external;
function burnFrom(address to, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract ICreditDesk {
uint256 public totalWritedowns;
uint256 public totalLoansOutstanding;
function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual;
function createCreditLine(
address _borrower,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) public virtual returns (address);
function drawdown(
uint256 amount,
address creditLineAddress,
address addressToSendTo
) external virtual;
function pay(address creditLineAddress, uint256 amount) external virtual;
function assessCreditLine(address creditLineAddress) external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../protocol/GoldfinchConfig.sol";
contract TestTheConfig {
address public poolAddress = 0xBAc2781706D0aA32Fb5928c9a5191A13959Dc4AE;
address public clImplAddress = 0xc783df8a850f42e7F7e57013759C285caa701eB6;
address public clFactoryAddress = 0x0afFE1972479c386A2Ab21a27a7f835361B6C0e9;
address public fiduAddress = 0xf3c9B38c155410456b5A98fD8bBf5E35B87F6d96;
address public creditDeskAddress = 0xeAD9C93b79Ae7C1591b1FB5323BD777E86e150d4;
address public treasuryReserveAddress = 0xECd9C93B79AE7C1591b1fB5323BD777e86E150d5;
function testTheEnums(address configAddress) public {
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TransactionLimit), 1);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.TotalFundsLimit), 2);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit), 3);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.ReserveDenominator), 4);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator), 5);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays), 6);
GoldfinchConfig(configAddress).setNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays), 7);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Fidu), fiduAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.Pool), poolAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CreditDesk), creditDeskAddress);
GoldfinchConfig(configAddress).setAddress(uint256(ConfigOptions.Addresses.CreditLineFactory), clFactoryAddress);
GoldfinchConfig(configAddress).setCreditLineImplementation(clImplAddress);
GoldfinchConfig(configAddress).setTreasuryReserve(treasuryReserveAddress);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../protocol/GoldfinchConfig.sol";
contract TestGoldfinchConfig is GoldfinchConfig {
function setAddressForTest(uint256 addressKey, address newAddress) public {
addresses[addressKey] = newAddress;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./BaseUpgradeablePausable.sol";
import "./GoldfinchConfig.sol";
/**
* @title CreditLineFactory
* @notice Contract that allows us to follow the minimal proxy pattern for creating CreditLines.
* This saves us gas, and lets us easily swap out the CreditLine implementaton.
* @author Goldfinch
*/
contract CreditLineFactory is BaseUpgradeablePausable {
GoldfinchConfig public config;
function initialize(address owner, GoldfinchConfig _config) public initializer {
__BaseUpgradeablePausable__init(owner);
config = _config;
}
function createCreditLine(bytes calldata _data) external returns (address) {
address creditLineImplAddress = config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation));
address creditLineProxy = deployMinimal(creditLineImplAddress, _data);
return creditLineProxy;
}
function deployMinimal(address _logic, bytes memory _data) internal returns (address proxy) {
/* solhint-disable */
// From https://github.com/OpenZeppelin/openzeppelin-sdk/blob/v2.8.0/packages/lib/contracts/upgradeability/ProxyFactory.sol#L18-L35
// Because of compiler version mismatch
bytes20 targetBytes = bytes20(_logic);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
// Only this line was changed (commented out)
// emit ProxyCreated(address(proxy));
if (_data.length > 0) {
(bool success, ) = proxy.call(_data);
require(success);
}
/* solhint-enable */
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../protocol/Pool.sol";
import "../protocol/BaseUpgradeablePausable.sol";
contract FakeV2CreditLine is BaseUpgradeablePausable {
// Credit line terms
address public borrower;
address public underwriter;
uint256 public limit;
uint256 public interestApr;
uint256 public paymentPeriodInDays;
uint256 public termInDays;
uint256 public lateFeeApr;
// Accounting variables
uint256 public balance;
uint256 public interestOwed;
uint256 public principalOwed;
uint256 public termEndBlock;
uint256 public nextDueBlock;
uint256 public interestAccruedAsOfBlock;
uint256 public writedownAmount;
uint256 public lastFullPaymentBlock;
function initialize(
address owner,
address _borrower,
address _underwriter,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) public initializer {
__BaseUpgradeablePausable__init(owner);
borrower = _borrower;
underwriter = _underwriter;
limit = _limit;
interestApr = _interestApr;
paymentPeriodInDays = _paymentPeriodInDays;
termInDays = _termInDays;
lateFeeApr = _lateFeeApr;
interestAccruedAsOfBlock = block.number;
}
function anotherNewFunction() external pure returns (uint256) {
return 42;
}
function authorizePool(address) external view onlyAdmin {
// no-op
return;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../protocol/Pool.sol";
contract TestPool is Pool {
function _getNumShares(uint256 amount) public view returns (uint256) {
return getNumShares(amount);
}
function _usdcMantissa() public view returns (uint256) {
return usdcMantissa();
}
function _fiduMantissa() public view returns (uint256) {
return fiduMantissa();
}
function _usdcToFidu(uint256 amount) public view returns (uint256) {
return usdcToFidu(amount);
}
function _setSharePrice(uint256 newSharePrice) public returns (uint256) {
sharePrice = newSharePrice;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-ethereum-package/contracts/presets/ERC20PresetMinterPauser.sol";
import "./ConfigHelper.sol";
/**
* @title Fidu
* @notice Fidu (symbol: FIDU) is Goldfinch's liquidity token, representing shares
* in the Pool. When you deposit, we mint a corresponding amount of Fidu, and when you withdraw, we
* burn Fidu. The share price of the Pool implicitly represents the "exchange rate" between Fidu
* and USDC (or whatever currencies the Pool may allow withdraws in during the future)
* @author Goldfinch
*/
contract Fidu is ERC20PresetMinterPauserUpgradeSafe {
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
// $1 threshold to handle potential rounding errors, from differing decimals on Fidu and USDC;
uint256 public constant ASSET_LIABILITY_MATCH_THRESHOLD = 1e6;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
/*
We are using our own initializer function so we can set the owner by passing it in.
I would override the regular "initializer" function, but I can't because it's not marked
as "virtual" in the parent contract
*/
// solhint-disable-next-line func-name-mixedcase
function __initialize__(
address owner,
string calldata name,
string calldata symbol,
GoldfinchConfig _config
) external initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
config = _config;
_setupRole(MINTER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(MINTER_ROLE, OWNER_ROLE);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mintTo(address to, uint256 amount) public {
require(canMint(amount), "Cannot mint: it would create an asset/liability mismatch");
// This will lock the function down to only the minter
super.mint(to, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have the MINTER_ROLE
*/
function burnFrom(address from, uint256 amount) public override {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: Must have minter role to burn");
require(canBurn(amount), "Cannot burn: it would create an asset/liability mismatch");
_burn(from, amount);
}
// Internal functions
// canMint assumes that the USDC that backs the new shares has already been sent to the Pool
function canMint(uint256 newAmount) internal view returns (bool) {
uint256 liabilities = totalSupply().add(newAmount).mul(config.getPool().sharePrice()).div(fiduMantissa());
uint256 liabilitiesInDollars = fiduToUSDC(liabilities);
uint256 _assets = config.getPool().assets();
if (_assets >= liabilitiesInDollars) {
return _assets.sub(liabilitiesInDollars) <= ASSET_LIABILITY_MATCH_THRESHOLD;
} else {
return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD;
}
}
// canBurn assumes that the USDC that backed these shares has already been moved out the Pool
function canBurn(uint256 amountToBurn) internal view returns (bool) {
uint256 liabilities = totalSupply().sub(amountToBurn).mul(config.getPool().sharePrice()).div(fiduMantissa());
uint256 liabilitiesInDollars = fiduToUSDC(liabilities);
uint256 _assets = config.getPool().assets();
if (_assets >= liabilitiesInDollars) {
return _assets.sub(liabilitiesInDollars) <= ASSET_LIABILITY_MATCH_THRESHOLD;
} else {
return liabilitiesInDollars.sub(_assets) <= ASSET_LIABILITY_MATCH_THRESHOLD;
}
}
function fiduToUSDC(uint256 amount) internal view returns (uint256) {
return amount.div(fiduMantissa().div(usdcMantissa()));
}
function fiduMantissa() internal view returns (uint256) {
return uint256(10)**uint256(decimals());
}
function usdcMantissa() internal view returns (uint256) {
return uint256(10)**uint256(config.getUSDC().decimals());
}
}
pragma solidity ^0.6.0;
import "../access/AccessControl.sol";
import "../GSN/Context.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Burnable.sol";
import "../token/ERC20/ERC20Pausable.sol";
import "../Initializable.sol";
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to aother accounts
*/
contract ERC20PresetMinterPauserUpgradeSafe is Initializable, ContextUpgradeSafe, AccessControlUpgradeSafe, ERC20BurnableUpgradeSafe, ERC20PausableUpgradeSafe {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
function initialize(string memory name, string memory symbol) public {
__ERC20PresetMinterPauser_init(name, symbol);
}
function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__ERC20PresetMinterPauser_init_unchained(name, symbol);
}
function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal override(ERC20UpgradeSafe, ERC20PausableUpgradeSafe) {
super._beforeTokenTransfer(from, to, amount);
}
uint256[50] private __gap;
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20MinterPauser}.
*
* 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 ERC20UpgradeSafe is Initializable, ContextUpgradeSafe, 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.
*/
function __ERC20_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name, symbol);
}
function __ERC20_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
_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 { }
uint256[44] private __gap;
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./ERC20.sol";
import "../../Initializable.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeSafe is Initializable, ContextUpgradeSafe, ERC20UpgradeSafe {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
uint256[50] private __gap;
}
pragma solidity ^0.6.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
import "../../Initializable.sol";
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeSafe is Initializable, ERC20UpgradeSafe, PausableUpgradeSafe {
function __ERC20Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
// contracts/GLDToken.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol";
contract TestERC20 is ERC20UpgradeSafe {
constructor(uint256 initialSupply, uint8 decimals) public {
__ERC20_init("USDC", "USDC");
_setupDecimals(decimals);
_mint(msg.sender, initialSupply);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "./ConfigHelper.sol";
import "./Accountant.sol";
import "./CreditLine.sol";
import "./CreditLineFactory.sol";
/**
* @title Goldfinch's CreditDesk contract
* @notice Main entry point for borrowers and underwriters.
* Handles key logic for creating CreditLine's, borrowing money, repayment, etc.
* @author Goldfinch
*/
contract CreditDesk is BaseUpgradeablePausable, ICreditDesk {
// Approximate number of blocks per day
uint256 public constant BLOCKS_PER_DAY = 5760;
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
struct Underwriter {
uint256 governanceLimit;
address[] creditLines;
}
struct Borrower {
address[] creditLines;
}
event PaymentApplied(
address indexed payer,
address indexed creditLine,
uint256 interestAmount,
uint256 principalAmount,
uint256 remainingAmount
);
event PaymentCollected(address indexed payer, address indexed creditLine, uint256 paymentAmount);
event DrawdownMade(address indexed borrower, address indexed creditLine, uint256 drawdownAmount);
event CreditLineCreated(address indexed borrower, address indexed creditLine);
event GovernanceUpdatedUnderwriterLimit(address indexed underwriter, uint256 newLimit);
mapping(address => Underwriter) public underwriters;
mapping(address => Borrower) private borrowers;
mapping(address => address) private creditLines;
/**
* @notice Run only once, on initialization
* @param owner The address of who should have the "OWNER_ROLE" of this contract
* @param _config The address of the GoldfinchConfig contract
*/
function initialize(address owner, GoldfinchConfig _config) public initializer {
__BaseUpgradeablePausable__init(owner);
config = _config;
}
/**
* @notice Sets a particular underwriter's limit of how much credit the DAO will allow them to "create"
* @param underwriterAddress The address of the underwriter for whom the limit shall change
* @param limit What the new limit will be set to
* Requirements:
*
* - the caller must have the `OWNER_ROLE`.
*/
function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit)
external
override
onlyAdmin
whenNotPaused
{
require(withinMaxUnderwriterLimit(limit), "This limit is greater than the max allowed by the protocol");
underwriters[underwriterAddress].governanceLimit = limit;
emit GovernanceUpdatedUnderwriterLimit(underwriterAddress, limit);
}
/**
* @notice Allows an underwriter to create a new CreditLine for a single borrower
* @param _borrower The borrower for whom the CreditLine will be created
* @param _limit The maximum amount a borrower can drawdown from this CreditLine
* @param _interestApr The interest amount, on an annualized basis (APR, so non-compounding), expressed as an integer.
* We assume 8 digits of precision. For example, to submit 15.34%, you would pass up 15340000,
* and 5.34% would be 5340000
* @param _paymentPeriodInDays How many days in each payment period.
* ie. the frequency with which they need to make payments.
* @param _termInDays Number of days in the credit term. It is used to set the `termEndBlock` upon first drawdown.
* ie. The credit line should be fully paid off {_termIndays} days after the first drawdown.
* @param _lateFeeApr The additional interest you will pay if you are late. For example, if this is 3%, and your
* normal rate is 15%, then you will pay 18% while you are late.
*
* Requirements:
*
* - the caller must be an underwriter with enough limit (see `setUnderwriterGovernanceLimit`)
*/
function createCreditLine(
address _borrower,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) public override whenNotPaused returns (address) {
Underwriter storage underwriter = underwriters[msg.sender];
Borrower storage borrower = borrowers[_borrower];
require(underwriterCanCreateThisCreditLine(_limit, underwriter), "The underwriter cannot create this credit line");
address clAddress = getCreditLineFactory().createCreditLine("");
CreditLine cl = CreditLine(clAddress);
cl.initialize(
address(this),
_borrower,
msg.sender,
_limit,
_interestApr,
_paymentPeriodInDays,
_termInDays,
_lateFeeApr
);
underwriter.creditLines.push(clAddress);
borrower.creditLines.push(clAddress);
creditLines[clAddress] = clAddress;
emit CreditLineCreated(_borrower, clAddress);
cl.grantRole(keccak256("OWNER_ROLE"), config.protocolAdminAddress());
cl.authorizePool(address(config));
return clAddress;
}
/**
* @notice Allows a borrower to drawdown on their creditline.
* `amount` USDC is sent to the borrower, and the credit line accounting is updated.
* @param amount The amount, in USDC atomic units, that a borrower wishes to drawdown
* @param creditLineAddress The creditline from which they would like to drawdown
* @param addressToSendTo The address where they would like the funds sent. If the zero address is passed,
* it will be defaulted to the borrower's address (msg.sender). This is a convenience feature for when they would
* like the funds sent to an exchange or alternate wallet, different from the authentication address
*
* Requirements:
*
* - the caller must be the borrower on the creditLine
*/
function drawdown(
uint256 amount,
address creditLineAddress,
address addressToSendTo
) external override whenNotPaused onlyValidCreditLine(creditLineAddress) {
CreditLine cl = CreditLine(creditLineAddress);
Borrower storage borrower = borrowers[msg.sender];
require(borrower.creditLines.length > 0, "No credit lines exist for this borrower");
require(amount > 0, "Must drawdown more than zero");
require(cl.borrower() == msg.sender, "You do not belong to this credit line");
require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
require(withinCreditLimit(amount, cl), "The borrower does not have enough credit limit for this drawdown");
if (addressToSendTo == address(0)) {
addressToSendTo = msg.sender;
}
if (cl.balance() == 0) {
cl.setInterestAccruedAsOfBlock(blockNumber());
cl.setLastFullPaymentBlock(blockNumber());
}
// Must get the interest and principal accrued prior to adding to the balance.
(uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, blockNumber());
uint256 balance = cl.balance().add(amount);
updateCreditLineAccounting(cl, balance, interestOwed, principalOwed);
// Must put this after we update the credit line accounting, so we're using the latest
// interestOwed
require(!isLate(cl), "Cannot drawdown when payments are past due");
emit DrawdownMade(msg.sender, address(cl), amount);
bool success = config.getPool().transferFrom(config.poolAddress(), addressToSendTo, amount);
require(success, "Failed to drawdown");
}
/**
* @notice Allows a borrower to repay their loan. Payment is *collected* immediately (by sending it to
* the individual CreditLine), but it is not *applied* unless it is after the nextDueBlock, or until we assess
* the credit line (ie. payment period end).
* Any amounts over the minimum payment will be applied to outstanding principal (reducing the effective
* interest rate). If there is still any left over, it will remain in the USDC Balance
* of the CreditLine, which is held distinct from the Pool amounts, and can not be withdrawn by LP's.
* @param creditLineAddress The credit line to be paid back
* @param amount The amount, in USDC atomic units, that a borrower wishes to pay
*/
function pay(address creditLineAddress, uint256 amount)
external
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
require(amount > 0, "Must pay more than zero");
CreditLine cl = CreditLine(creditLineAddress);
collectPayment(cl, amount);
assessCreditLine(creditLineAddress);
}
/**
* @notice Assesses a particular creditLine. This will apply payments, which will update accounting and
* distribute gains or losses back to the pool accordingly. This function is idempotent, and anyone
* is allowed to call it.
* @param creditLineAddress The creditline that should be assessed.
*/
function assessCreditLine(address creditLineAddress)
public
override
whenNotPaused
onlyValidCreditLine(creditLineAddress)
{
CreditLine cl = CreditLine(creditLineAddress);
// Do not assess until a full period has elapsed or past due
require(cl.balance() > 0, "Must have balance to assess credit line");
// Don't assess credit lines early!
if (blockNumber() < cl.nextDueBlock() && !isLate(cl)) {
return;
}
cl.setNextDueBlock(calculateNextDueBlock(cl));
uint256 blockToAssess = cl.nextDueBlock();
// We always want to assess for the most recently *past* nextDueBlock.
// So if the recalculation above sets the nextDueBlock into the future,
// then ensure we pass in the one just before this.
if (cl.nextDueBlock() > blockNumber()) {
uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY);
blockToAssess = cl.nextDueBlock().sub(blocksPerPeriod);
}
applyPayment(cl, getUSDCBalance(address(cl)), blockToAssess);
}
function migrateCreditLine(
CreditLine clToMigrate,
address _borrower,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr
) public onlyAdmin {
require(clToMigrate.limit() > 0, "Can't migrate empty credit line");
address newClAddress =
createCreditLine(_borrower, _limit, _interestApr, _paymentPeriodInDays, _termInDays, _lateFeeApr);
CreditLine newCl = CreditLine(newClAddress);
// Set accounting state vars.
newCl.setBalance(clToMigrate.balance());
newCl.setInterestOwed(clToMigrate.interestOwed());
newCl.setPrincipalOwed(clToMigrate.principalOwed());
newCl.setTermEndBlock(clToMigrate.termEndBlock());
newCl.setNextDueBlock(clToMigrate.nextDueBlock());
newCl.setInterestAccruedAsOfBlock(clToMigrate.interestAccruedAsOfBlock());
newCl.setWritedownAmount(clToMigrate.writedownAmount());
newCl.setLastFullPaymentBlock(clToMigrate.lastFullPaymentBlock());
// Close out the original credit line
clToMigrate.setLimit(0);
clToMigrate.setBalance(0);
bool success =
config.getPool().transferFrom(
address(clToMigrate),
address(newCl),
config.getUSDC().balanceOf(address(clToMigrate))
);
require(success, "Failed to transfer funds");
}
// Public View Functions (Getters)
/**
* @notice Simple getter for the creditlines of a given underwriter
* @param underwriterAddress The underwriter address you would like to see the credit lines of.
*/
function getUnderwriterCreditLines(address underwriterAddress) public view whenNotPaused returns (address[] memory) {
return underwriters[underwriterAddress].creditLines;
}
/**
* @notice Simple getter for the creditlines of a given borrower
* @param borrowerAddress The borrower address you would like to see the credit lines of.
*/
function getBorrowerCreditLines(address borrowerAddress) public view whenNotPaused returns (address[] memory) {
return borrowers[borrowerAddress].creditLines;
}
/*
* Internal Functions
*/
/**
* @notice Collects `amount` of payment for a given credit line. This sends money from the payer to the credit line.
* Note that payment is not *applied* when calling this function. Only collected (ie. held) for later application.
* @param cl The CreditLine the payment will be collected for.
* @param amount The amount, in USDC atomic units, to be collected
*/
function collectPayment(CreditLine cl, uint256 amount) internal {
require(withinTransactionLimit(amount), "Amount is over the per-transaction limit");
require(config.getUSDC().balanceOf(msg.sender) >= amount, "You have insufficent balance for this payment");
emit PaymentCollected(msg.sender, address(cl), amount);
bool success = config.getPool().transferFrom(msg.sender, address(cl), amount);
require(success, "Failed to collect payment");
}
/**
* @notice Applies `amount` of payment for a given credit line. This moves already collected money into the Pool.
* It also updates all the accounting variables. Note that interest is always paid back first, then principal.
* Any extra after paying the minimum will go towards existing principal (reducing the
* effective interest rate). Any extra after the full loan has been paid off will remain in the
* USDC Balance of the creditLine, where it will be automatically used for the next drawdown.
* @param cl The CreditLine the payment will be collected for.
* @param amount The amount, in USDC atomic units, to be applied
* @param blockNumber The blockNumber on which accrual calculations should be based. This allows us
* to be precise when we assess a Credit Line
*/
function applyPayment(
CreditLine cl,
uint256 amount,
uint256 blockNumber
) internal {
(uint256 paymentRemaining, uint256 interestPayment, uint256 principalPayment) =
handlePayment(cl, amount, blockNumber);
updateWritedownAmounts(cl);
if (interestPayment > 0) {
emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining);
config.getPool().collectInterestRepayment(address(cl), interestPayment);
}
if (principalPayment > 0) {
emit PaymentApplied(cl.borrower(), address(cl), interestPayment, principalPayment, paymentRemaining);
config.getPool().collectPrincipalRepayment(address(cl), principalPayment);
}
}
function handlePayment(
CreditLine cl,
uint256 paymentAmount,
uint256 asOfBlock
)
internal
returns (
uint256,
uint256,
uint256
)
{
(uint256 interestOwed, uint256 principalOwed) = updateAndGetInterestAndPrincipalOwedAsOf(cl, asOfBlock);
Accountant.PaymentAllocation memory pa =
Accountant.allocatePayment(paymentAmount, cl.balance(), interestOwed, principalOwed);
uint256 newBalance = cl.balance().sub(pa.principalPayment);
// Apply any additional payment towards the balance
newBalance = newBalance.sub(pa.additionalBalancePayment);
uint256 totalPrincipalPayment = cl.balance().sub(newBalance);
uint256 paymentRemaining = paymentAmount.sub(pa.interestPayment).sub(totalPrincipalPayment);
updateCreditLineAccounting(
cl,
newBalance,
interestOwed.sub(pa.interestPayment),
principalOwed.sub(pa.principalPayment)
);
assert(paymentRemaining.add(pa.interestPayment).add(totalPrincipalPayment) == paymentAmount);
return (paymentRemaining, pa.interestPayment, totalPrincipalPayment);
}
function updateWritedownAmounts(CreditLine cl) internal {
(uint256 writedownPercent, uint256 writedownAmount) =
Accountant.calculateWritedownFor(
cl,
blockNumber(),
config.getLatenessGracePeriodInDays(),
config.getLatenessMaxDays()
);
if (writedownPercent == 0 && cl.writedownAmount() == 0) {
return;
}
int256 writedownDelta = int256(cl.writedownAmount()) - int256(writedownAmount);
cl.setWritedownAmount(writedownAmount);
if (writedownDelta > 0) {
// If writedownDelta is positive, that means we got money back. So subtract from totalWritedowns.
totalWritedowns = totalWritedowns.sub(uint256(writedownDelta));
} else {
totalWritedowns = totalWritedowns.add(uint256(writedownDelta * -1));
}
config.getPool().distributeLosses(address(cl), writedownDelta);
}
function isLate(CreditLine cl) internal view returns (bool) {
uint256 blocksElapsedSinceFullPayment = blockNumber().sub(cl.lastFullPaymentBlock());
return blocksElapsedSinceFullPayment > cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY);
}
function getCreditLineFactory() internal view returns (CreditLineFactory) {
return CreditLineFactory(config.getAddress(uint256(ConfigOptions.Addresses.CreditLineFactory)));
}
function subtractClFromTotalLoansOutstanding(CreditLine cl) internal {
totalLoansOutstanding = totalLoansOutstanding.sub(cl.balance());
}
function addCLToTotalLoansOutstanding(CreditLine cl) internal {
totalLoansOutstanding = totalLoansOutstanding.add(cl.balance());
}
function updateAndGetInterestAndPrincipalOwedAsOf(CreditLine cl, uint256 blockNumber)
internal
returns (uint256, uint256)
{
(uint256 interestAccrued, uint256 principalAccrued) =
Accountant.calculateInterestAndPrincipalAccrued(cl, blockNumber, config.getLatenessGracePeriodInDays());
if (interestAccrued > 0) {
// If we've accrued any interest, update interestAccruedAsOfBLock to the block that we've
// calculated interest for. If we've not accrued any interest, then we keep the old value so the next
// time the entire period is taken into account.
cl.setInterestAccruedAsOfBlock(blockNumber);
}
return (cl.interestOwed().add(interestAccrued), cl.principalOwed().add(principalAccrued));
}
function withinCreditLimit(uint256 amount, CreditLine cl) internal view returns (bool) {
return cl.balance().add(amount) <= cl.limit();
}
function withinTransactionLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.TransactionLimit));
}
function calculateNewTermEndBlock(CreditLine cl) internal view returns (uint256) {
// If there's no balance, there's no loan, so there's no term end block
if (cl.balance() == 0) {
return 0;
}
// Don't allow any weird bugs where we add to your current end block. This
// function should only be used on new credit lines, when we are setting them up
if (cl.termEndBlock() != 0) {
return cl.termEndBlock();
}
return blockNumber().add(BLOCKS_PER_DAY.mul(cl.termInDays()));
}
function calculateNextDueBlock(CreditLine cl) internal view returns (uint256) {
uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY);
// Your paid off, or have not taken out a loan yet, so no next due block.
if (cl.balance() == 0 && cl.nextDueBlock() != 0) {
return 0;
}
// You must have just done your first drawdown
if (cl.nextDueBlock() == 0 && cl.balance() > 0) {
return blockNumber().add(blocksPerPeriod);
}
// Active loan that has entered a new period, so return the *next* nextDueBlock.
// But never return something after the termEndBlock
if (cl.balance() > 0 && blockNumber() >= cl.nextDueBlock()) {
uint256 blocksToAdvance = (blockNumber().sub(cl.nextDueBlock()).div(blocksPerPeriod)).add(1).mul(blocksPerPeriod);
uint256 nextDueBlock = cl.nextDueBlock().add(blocksToAdvance);
return Math.min(nextDueBlock, cl.termEndBlock());
}
// Active loan in current period, where we've already set the nextDueBlock correctly, so should not change.
if (cl.balance() > 0 && blockNumber() < cl.nextDueBlock()) {
return cl.nextDueBlock();
}
revert("Error: could not calculate next due block.");
}
function blockNumber() internal view virtual returns (uint256) {
return block.number;
}
function underwriterCanCreateThisCreditLine(uint256 newAmount, Underwriter storage underwriter)
internal
view
returns (bool)
{
require(underwriter.governanceLimit != 0, "underwriter does not have governance limit");
uint256 creditCurrentlyExtended = getCreditCurrentlyExtended(underwriter);
uint256 totalToBeExtended = creditCurrentlyExtended.add(newAmount);
return totalToBeExtended <= underwriter.governanceLimit;
}
function withinMaxUnderwriterLimit(uint256 amount) internal view returns (bool) {
return amount <= config.getNumber(uint256(ConfigOptions.Numbers.MaxUnderwriterLimit));
}
function getCreditCurrentlyExtended(Underwriter storage underwriter) internal view returns (uint256) {
uint256 creditExtended;
uint256 length = underwriter.creditLines.length;
for (uint256 i = 0; i < length; i++) {
CreditLine cl = CreditLine(underwriter.creditLines[i]);
creditExtended = creditExtended.add(cl.limit());
}
return creditExtended;
}
function updateCreditLineAccounting(
CreditLine cl,
uint256 balance,
uint256 interestOwed,
uint256 principalOwed
) internal nonReentrant {
subtractClFromTotalLoansOutstanding(cl);
cl.setBalance(balance);
cl.setInterestOwed(interestOwed);
cl.setPrincipalOwed(principalOwed);
// This resets lastFullPaymentBlock. These conditions assure that they have
// indeed paid off all their interest and they have a real nextDueBlock. (ie. creditline isn't pre-drawdown)
if (cl.interestOwed() == 0 && cl.nextDueBlock() != 0) {
// If interest was fully paid off, then set the last full payment as the previous due block
uint256 mostRecentLastDueBlock;
if (blockNumber() < cl.nextDueBlock()) {
uint256 blocksPerPeriod = cl.paymentPeriodInDays().mul(BLOCKS_PER_DAY);
mostRecentLastDueBlock = cl.nextDueBlock().sub(blocksPerPeriod);
} else {
mostRecentLastDueBlock = cl.nextDueBlock();
}
cl.setLastFullPaymentBlock(mostRecentLastDueBlock);
}
addCLToTotalLoansOutstanding(cl);
cl.setTermEndBlock(calculateNewTermEndBlock(cl));
cl.setNextDueBlock(calculateNextDueBlock(cl));
}
function getUSDCBalance(address _address) internal returns (uint256) {
return config.getUSDC().balanceOf(_address);
}
modifier onlyValidCreditLine(address clAddress) {
require(creditLines[clAddress] != address(0), "Unknown credit line");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../protocol/CreditDesk.sol";
contract TestCreditDesk is CreditDesk {
uint256 _blockNumberForTest;
function _setTotalLoansOutstanding(uint256 amount) public {
totalLoansOutstanding = amount;
}
function _setBlockNumberForTest(uint256 blockNumber) public {
_blockNumberForTest = blockNumber;
}
function blockNumber() internal view override returns (uint256) {
if (_blockNumberForTest == 0) {
return super.blockNumber();
} else {
return _blockNumberForTest;
}
}
function blockNumberForTest() public view returns (uint256) {
return blockNumber();
}
}
| Scaling factor used by FixedPoint.sol. We need this to convert the fixed point raw values back to unscaled | library Accountant {
using SafeMath for uint256;
using FixedPoint for FixedPoint.Signed;
using FixedPoint for FixedPoint.Unsigned;
using FixedPoint for int256;
using FixedPoint for uint256;
uint256 public constant FP_SCALING_FACTOR = 10**18;
uint256 public constant INTEREST_DECIMALS = 1e8;
uint256 public constant BLOCKS_PER_DAY = 5760;
uint256 public constant BLOCKS_PER_YEAR = (BLOCKS_PER_DAY * 365);
struct PaymentAllocation {
uint256 interestPayment;
uint256 principalPayment;
uint256 additionalBalancePayment;
}
function calculateInterestAndPrincipalAccrued(
CreditLine cl,
uint256 blockNumber,
uint256 lateFeeGracePeriod
) public view returns (uint256, uint256) {
uint256 interestAccrued = calculateInterestAccrued(cl, blockNumber, lateFeeGracePeriod);
uint256 principalAccrued = calculatePrincipalAccrued(cl, blockNumber);
return (interestAccrued, principalAccrued);
}
function calculatePrincipalAccrued(CreditLine cl, uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= cl.termEndBlock()) {
return cl.balance();
return 0;
}
}
function calculatePrincipalAccrued(CreditLine cl, uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= cl.termEndBlock()) {
return cl.balance();
return 0;
}
}
} else {
function calculateWritedownFor(
CreditLine cl,
uint256 blockNumber,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl);
if (amountOwedPerDay.isEqual(0)) {
return (0, 0);
}
FixedPoint.Unsigned memory fpGracePeriod =
FixedPoint.min(
FixedPoint.fromUnscaledUint(gracePeriodInDays),
FixedPoint.fromUnscaledUint(cl.paymentPeriodInDays())
);
FixedPoint.Unsigned memory daysLate;
daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay);
if (blockNumber > cl.termEndBlock()) {
uint256 blocksLate = blockNumber.sub(cl.termEndBlock());
daysLate = daysLate.add(FixedPoint.fromUnscaledUint(blocksLate).div(BLOCKS_PER_DAY));
}
FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate);
FixedPoint.Unsigned memory writedownPercent;
if (daysLate.isLessThanOrEqual(fpGracePeriod)) {
writedownPercent = FixedPoint.fromUnscaledUint(0);
writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate));
}
FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(cl.balance()).div(FP_SCALING_FACTOR);
return (unscaledWritedownPercent, writedownAmount.rawValue);
}
function calculateWritedownFor(
CreditLine cl,
uint256 blockNumber,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl);
if (amountOwedPerDay.isEqual(0)) {
return (0, 0);
}
FixedPoint.Unsigned memory fpGracePeriod =
FixedPoint.min(
FixedPoint.fromUnscaledUint(gracePeriodInDays),
FixedPoint.fromUnscaledUint(cl.paymentPeriodInDays())
);
FixedPoint.Unsigned memory daysLate;
daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay);
if (blockNumber > cl.termEndBlock()) {
uint256 blocksLate = blockNumber.sub(cl.termEndBlock());
daysLate = daysLate.add(FixedPoint.fromUnscaledUint(blocksLate).div(BLOCKS_PER_DAY));
}
FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate);
FixedPoint.Unsigned memory writedownPercent;
if (daysLate.isLessThanOrEqual(fpGracePeriod)) {
writedownPercent = FixedPoint.fromUnscaledUint(0);
writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate));
}
FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(cl.balance()).div(FP_SCALING_FACTOR);
return (unscaledWritedownPercent, writedownAmount.rawValue);
}
uint256 totalOwed = cl.interestOwed().add(cl.principalOwed());
function calculateWritedownFor(
CreditLine cl,
uint256 blockNumber,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl);
if (amountOwedPerDay.isEqual(0)) {
return (0, 0);
}
FixedPoint.Unsigned memory fpGracePeriod =
FixedPoint.min(
FixedPoint.fromUnscaledUint(gracePeriodInDays),
FixedPoint.fromUnscaledUint(cl.paymentPeriodInDays())
);
FixedPoint.Unsigned memory daysLate;
daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay);
if (blockNumber > cl.termEndBlock()) {
uint256 blocksLate = blockNumber.sub(cl.termEndBlock());
daysLate = daysLate.add(FixedPoint.fromUnscaledUint(blocksLate).div(BLOCKS_PER_DAY));
}
FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate);
FixedPoint.Unsigned memory writedownPercent;
if (daysLate.isLessThanOrEqual(fpGracePeriod)) {
writedownPercent = FixedPoint.fromUnscaledUint(0);
writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate));
}
FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(cl.balance()).div(FP_SCALING_FACTOR);
return (unscaledWritedownPercent, writedownAmount.rawValue);
}
function calculateWritedownFor(
CreditLine cl,
uint256 blockNumber,
uint256 gracePeriodInDays,
uint256 maxDaysLate
) public view returns (uint256, uint256) {
FixedPoint.Unsigned memory amountOwedPerDay = calculateAmountOwedForOneDay(cl);
if (amountOwedPerDay.isEqual(0)) {
return (0, 0);
}
FixedPoint.Unsigned memory fpGracePeriod =
FixedPoint.min(
FixedPoint.fromUnscaledUint(gracePeriodInDays),
FixedPoint.fromUnscaledUint(cl.paymentPeriodInDays())
);
FixedPoint.Unsigned memory daysLate;
daysLate = FixedPoint.fromUnscaledUint(totalOwed).div(amountOwedPerDay);
if (blockNumber > cl.termEndBlock()) {
uint256 blocksLate = blockNumber.sub(cl.termEndBlock());
daysLate = daysLate.add(FixedPoint.fromUnscaledUint(blocksLate).div(BLOCKS_PER_DAY));
}
FixedPoint.Unsigned memory maxLate = FixedPoint.fromUnscaledUint(maxDaysLate);
FixedPoint.Unsigned memory writedownPercent;
if (daysLate.isLessThanOrEqual(fpGracePeriod)) {
writedownPercent = FixedPoint.fromUnscaledUint(0);
writedownPercent = FixedPoint.min(FixedPoint.fromUnscaledUint(1), (daysLate.sub(fpGracePeriod)).div(maxLate));
}
FixedPoint.Unsigned memory writedownAmount = writedownPercent.mul(cl.balance()).div(FP_SCALING_FACTOR);
return (unscaledWritedownPercent, writedownAmount.rawValue);
}
} else {
uint256 unscaledWritedownPercent = writedownPercent.mul(100).div(FP_SCALING_FACTOR).rawValue;
function calculateAmountOwedForOneDay(CreditLine cl) public view returns (FixedPoint.Unsigned memory) {
uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS);
FixedPoint.Unsigned memory interestOwed = FixedPoint.fromUnscaledUint(totalInterestPerYear).div(365);
return interestOwed;
}
function calculateInterestAccrued(
CreditLine cl,
uint256 blockNumber,
uint256 lateFeeGracePeriodInDays
) public view returns (uint256) {
uint256 interestAccruedAsOfBlock = Math.min(blockNumber, cl.interestAccruedAsOfBlock());
uint256 numBlocksElapsed = blockNumber.sub(interestAccruedAsOfBlock);
uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS);
uint256 interestOwed = totalInterestPerYear.mul(numBlocksElapsed).div(BLOCKS_PER_YEAR);
if (lateFeeApplicable(cl, blockNumber, lateFeeGracePeriodInDays)) {
uint256 lateFeeInterestPerYear = cl.balance().mul(cl.lateFeeApr()).div(INTEREST_DECIMALS);
uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(numBlocksElapsed).div(BLOCKS_PER_YEAR);
interestOwed = interestOwed.add(additionalLateFeeInterest);
}
return interestOwed;
}
function calculateInterestAccrued(
CreditLine cl,
uint256 blockNumber,
uint256 lateFeeGracePeriodInDays
) public view returns (uint256) {
uint256 interestAccruedAsOfBlock = Math.min(blockNumber, cl.interestAccruedAsOfBlock());
uint256 numBlocksElapsed = blockNumber.sub(interestAccruedAsOfBlock);
uint256 totalInterestPerYear = cl.balance().mul(cl.interestApr()).div(INTEREST_DECIMALS);
uint256 interestOwed = totalInterestPerYear.mul(numBlocksElapsed).div(BLOCKS_PER_YEAR);
if (lateFeeApplicable(cl, blockNumber, lateFeeGracePeriodInDays)) {
uint256 lateFeeInterestPerYear = cl.balance().mul(cl.lateFeeApr()).div(INTEREST_DECIMALS);
uint256 additionalLateFeeInterest = lateFeeInterestPerYear.mul(numBlocksElapsed).div(BLOCKS_PER_YEAR);
interestOwed = interestOwed.add(additionalLateFeeInterest);
}
return interestOwed;
}
function lateFeeApplicable(
CreditLine cl,
uint256 blockNumber,
uint256 gracePeriodInDays
) public view returns (bool) {
uint256 blocksLate = blockNumber.sub(cl.lastFullPaymentBlock());
gracePeriodInDays = Math.min(gracePeriodInDays, cl.paymentPeriodInDays());
return cl.lateFeeApr() > 0 && blocksLate > gracePeriodInDays.mul(BLOCKS_PER_DAY);
}
function allocatePayment(
uint256 paymentAmount,
uint256 balance,
uint256 interestOwed,
uint256 principalOwed
) public pure returns (PaymentAllocation memory) {
uint256 paymentRemaining = paymentAmount;
uint256 interestPayment = Math.min(interestOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(interestPayment);
uint256 principalPayment = Math.min(principalOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(principalPayment);
uint256 balanceRemaining = balance.sub(principalPayment);
uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining);
return
PaymentAllocation({
interestPayment: interestPayment,
principalPayment: principalPayment,
additionalBalancePayment: additionalBalancePayment
});
}
function allocatePayment(
uint256 paymentAmount,
uint256 balance,
uint256 interestOwed,
uint256 principalOwed
) public pure returns (PaymentAllocation memory) {
uint256 paymentRemaining = paymentAmount;
uint256 interestPayment = Math.min(interestOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(interestPayment);
uint256 principalPayment = Math.min(principalOwed, paymentRemaining);
paymentRemaining = paymentRemaining.sub(principalPayment);
uint256 balanceRemaining = balance.sub(principalPayment);
uint256 additionalBalancePayment = Math.min(paymentRemaining, balanceRemaining);
return
PaymentAllocation({
interestPayment: interestPayment,
principalPayment: principalPayment,
additionalBalancePayment: additionalBalancePayment
});
}
}
| 1,093,570 | [
1,
8471,
5578,
1399,
635,
15038,
2148,
18,
18281,
18,
1660,
1608,
333,
358,
1765,
326,
5499,
1634,
1831,
924,
1473,
358,
16804,
12825,
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,
12083,
6590,
970,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
225,
1450,
15038,
2148,
364,
15038,
2148,
18,
12294,
31,
203,
225,
1450,
15038,
2148,
364,
15038,
2148,
18,
13290,
31,
203,
225,
1450,
15038,
2148,
364,
509,
5034,
31,
203,
225,
1450,
15038,
2148,
364,
2254,
5034,
31,
203,
203,
225,
2254,
5034,
1071,
5381,
28740,
67,
2312,
1013,
1360,
67,
26835,
273,
1728,
636,
2643,
31,
203,
225,
2254,
5034,
1071,
5381,
11391,
11027,
67,
23816,
55,
273,
404,
73,
28,
31,
203,
225,
2254,
5034,
1071,
5381,
14073,
55,
67,
3194,
67,
10339,
273,
15981,
4848,
31,
203,
225,
2254,
5034,
1071,
5381,
14073,
55,
67,
3194,
67,
15137,
273,
261,
11403,
55,
67,
3194,
67,
10339,
380,
21382,
1769,
203,
203,
203,
203,
225,
1958,
12022,
17353,
288,
203,
565,
2254,
5034,
16513,
6032,
31,
203,
565,
2254,
5034,
8897,
6032,
31,
203,
565,
2254,
5034,
3312,
13937,
6032,
31,
203,
225,
289,
203,
203,
225,
445,
4604,
29281,
1876,
9155,
8973,
86,
5957,
12,
203,
565,
30354,
1670,
927,
16,
203,
565,
2254,
5034,
1203,
1854,
16,
203,
565,
2254,
5034,
26374,
14667,
24443,
5027,
203,
225,
262,
1071,
1476,
1135,
261,
11890,
5034,
16,
2254,
5034,
13,
288,
203,
565,
2254,
5034,
16513,
8973,
86,
5957,
273,
4604,
29281,
8973,
86,
5957,
12,
830,
16,
1203,
1854,
16,
26374,
14667,
24443,
5027,
1769,
203,
565,
2254,
5034,
8897,
8973,
86,
5957,
273,
4604,
9155,
8973,
86,
5957,
12,
830,
16,
1203,
1854,
1769,
203,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-14
*/
// File: contracts/HolyHandV5.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
///////////////////////////////////////////////////////////////////////////
// __/|
// __//// /| This smart contract is part of Mover infrastructure
// |// //_/// https://viamover.com
// |_/ // [email protected]
// |/
///////////////////////////////////////////////////////////////////////////
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// 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;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 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 ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @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");
}
}
}
// Interface to represent asset pool interactions
interface IHolyPoolV2 {
function getBaseAsset() external view returns(address);
// functions callable by HolyHand transfer proxy
function depositOnBehalf(address beneficiary, uint256 amount) external;
function depositOnBehalfDirect(address beneficiary, uint256 amount) external;
function withdraw(address beneficiary, uint256 amount) external;
// functions callable by HolyValor investment proxies
// pool would transfer funds to HolyValor (returns actual amount, could be less than asked)
function borrowToInvest(uint256 amount) external returns(uint256);
// return invested body portion from HolyValor (pool will claim base assets from caller Valor)
function returnInvested(uint256 amountCapitalBody) external;
// functions callable by HolyRedeemer yield distributor
function harvestYield(uint256 amount) external; // pool would transfer amount tokens from caller as it's profits
}
// Interface to represent middleware contract for swapping tokens
interface IHolyWing {
// returns amount of 'destination token' that 'source token' was swapped to
// NOTE: HolyWing grants allowance to arbitrary address (with call to contract that could be forged) and should not hold any funds
function executeSwap(address tokenFrom, address tokenTo, uint256 amount, bytes calldata data) external returns(uint256);
}
// Interface to represent middleware contract for swapping tokens
interface IHolyWingV2 {
// returns amount of 'destination token' that 'source token' was swapped to
// NOTE: HolyWing grants allowance to arbitrary address (with call to contract that could be forged) and should not hold any funds
function executeSwap(address tokenFrom, address tokenTo, uint256 amount, bytes calldata data) payable external returns(uint256);
function executeSwapDirect(address beneficiary, address tokenFrom, address tokenTo, uint256 amount, uint256 fee, bytes calldata data) payable external returns(uint256);
}
// Interface to represent middleware contract for distributing profits
interface IHolyRedeemer {
}
// Interface to represent asset pool interactions
interface ISmartTreasury {
function spendBonus(address _account, uint256 _amount) external;
function depositOnBehalf(address _account, uint _tokenMoveAmount, uint _tokenMoveEthAmount) external;
function claimAndBurnOnBehalf(address _beneficiary, uint256 _amount) external;
}
// Interface to represent burnable ERC20 tokens
interface IBurnable {
function burn(uint256 amount) external;
function burnFrom(address account, uint256 amount) external;
}
interface IChainLinkFeed {
function latestAnswer() external view returns (int256);
}
abstract contract SafeAllowanceReset {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// this function exists due to OpenZeppelin quirks in safe allowance-changing methods
// we don't want to set allowance by small chunks as it would cost more gas for users
// and we don't want to set it to zero and then back to value (this makes no sense security-wise in single tx)
// from the other side, using it through safeIncreaseAllowance could revery due to SafeMath overflow
// Therefore, we calculate what amount we can increase allowance on to refill it to max uint256 value
function resetAllowanceIfNeeded(IERC20 _token, address _spender, uint256 _amount) internal {
uint256 allowance = _token.allowance(address(this), _spender);
if (allowance < _amount) {
uint256 newAllowance = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
IERC20(_token).safeIncreaseAllowance(address(_spender), newAllowance.sub(allowance));
}
}
}
/*
HolyHand is a transfer proxy contract for ERC20 and ETH transfers through Holyheld infrastructure (deposit/withdraw to HolyPool, swaps, etc.)
- extract fees;
- call token conversion if needed;
- deposit/withdraw tokens into HolyPool;
- non-custodial, not holding any funds;
- fees are accumulated on this contract's balance (if fees enabled);
This contract is a single address that user grants allowance to on any ERC20 token for interacting with HH services.
This contract could be upgraded in the future to provide subsidized transactions using bonuses from treasury.
TODO: if token supports permit, provide ability to execute without separate approval call
V2 version additions:
- direct deposits to pool (if no fees or conversions);
- when swapping tokens direct return converted asset to sender (if no fees);
- ETH support (non-wrapped ETH conversion for deposits and swaps);
- emergencyTransfer can reclaim ETH
V3 version additions:
- support for subsidized transaction execution;
V4 version additions:
- support for subsidized treasury deposit/withdrawals;
- bonus spending parameter using USDC/USD price data from chainlink (feature-flagged)
V5 version additions:
- cardTopUp method added that converts to USDC if needed, creates event and transfers to partner account on user behalf
*/
contract HolyHandV5_1 is AccessControlUpgradeable, SafeAllowanceReset {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address payable;
uint256 private constant ALLOWANCE_SIZE =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// token address for non-wrapped eth
address private constant ETH_TOKEN_ADDRESS =
0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// if greater than zero, this is a fractional amount (1e18 = 1.0) fee applied to all deposits
uint256 public depositFee;
// if greater than zero, this is a fractional amount (1e18 = 1.0) fee applied to exchange operations with HolyWing proxy
uint256 public exchangeFee;
// if greater than zero, this is a fractional amount (1e18 = 1.0) fee applied to withdraw operations
uint256 public withdrawFee;
// HolyWing exchange proxy/middleware
IHolyWing private exchangeProxyContract;
// HolyRedeemer yield distributor
// NOTE: to keep overhead for users minimal, fees are not transferred
// immediately, but left on this contract balance, yieldDistributor can reclaim them
address private yieldDistributorAddress;
event TokenSwap(
address indexed tokenFrom,
address indexed tokenTo,
address sender,
uint256 amountFrom,
uint256 expectedMinimumReceived,
uint256 amountReceived
);
event FeeChanged(string indexed name, uint256 value);
event EmergencyTransfer(
address indexed token,
address indexed destination,
uint256 amount
);
function initialize() public initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
depositFee = 0;
exchangeFee = 0;
withdrawFee = 0;
}
function setExchangeProxy(address _exchangeProxyContract) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
exchangeProxyContract = IHolyWing(_exchangeProxyContract);
}
function setYieldDistributor(
address _tokenAddress,
address _distributorAddress
) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
yieldDistributorAddress = _distributorAddress;
// only yield to be redistributed should be present on this contract in baseAsset (or other tokens if swap fees)
// so no access to lp tokens for the funds invested
resetAllowanceIfNeeded(
IERC20(_tokenAddress),
_distributorAddress,
ALLOWANCE_SIZE
);
}
// if the pool baseToken matches the token deposited, then no conversion is performed
// and _expectedMininmumReceived/convertData should be zero/empty
function depositToPool(
address _poolAddress,
address _token,
uint256 _amount,
uint256 _expectedMinimumReceived,
bytes memory _convertData
) public payable {
depositToPoolOnBehalf(msg.sender, _poolAddress, _token, _amount, _expectedMinimumReceived, _convertData);
}
function depositToPoolOnBehalf(
address _beneficiary,
address _poolAddress,
address _token,
uint256 _amount,
uint256 _expectedMinimumReceived,
bytes memory _convertData
) internal {
IHolyPoolV2 holyPool = IHolyPoolV2(_poolAddress);
IERC20 poolToken = IERC20(holyPool.getBaseAsset());
if (address(poolToken) == _token) {
// no conversion is needed, allowance and balance checks performed in ERC20 token
// and not here to not waste any gas fees
if (depositFee == 0) {
// use depositOnBehalfDirect function only for this flow to save gas as much as possible
// (we have approval for this contract, so it can transfer funds to pool directly if
// deposit fees are zero (otherwise we go with standard processing flow)
// transfer directly to pool
IERC20(_token).safeTransferFrom(
_beneficiary,
_poolAddress,
_amount
);
// call pool function to process deposit (without transfer)
holyPool.depositOnBehalfDirect(_beneficiary, _amount);
return;
}
IERC20(_token).safeTransferFrom(_beneficiary, address(this), _amount);
// HolyPool must have sufficient allowance (one-time for pool/token pair)
resetAllowanceIfNeeded(poolToken, _poolAddress, _amount);
// process deposit fees and deposit remainder
uint256 feeAmount = _amount.mul(depositFee).div(1e18);
holyPool.depositOnBehalf(_beneficiary, _amount.sub(feeAmount));
return;
}
// conversion is required, perform swap through exchangeProxy (HolyWing)
if (_token != ETH_TOKEN_ADDRESS) {
IERC20(_token).safeTransferFrom(
_beneficiary,
address(exchangeProxyContract),
_amount
);
}
if (depositFee > 0) {
// process exchange/deposit fees and route through HolyHand
uint256 amountReceived =
IHolyWingV2(address(exchangeProxyContract)).executeSwapDirect{value: msg.value}(
address(this),
_token,
address(poolToken),
_amount,
exchangeFee,
_convertData
);
require(
amountReceived >= _expectedMinimumReceived,
"minimum swap amount not met"
);
uint256 feeAmount = amountReceived.mul(depositFee).div(1e18);
amountReceived = amountReceived.sub(feeAmount);
// HolyPool must have sufficient allowance (one-time for pool/token pair)
resetAllowanceIfNeeded(poolToken, _poolAddress, _amount);
// perform actual deposit call
holyPool.depositOnBehalf(_beneficiary, amountReceived);
} else {
// swap directly to HolyPool address and execute direct deposit call
uint256 amountReceived =
IHolyWingV2(address(exchangeProxyContract)).executeSwapDirect{value: msg.value}(
_poolAddress,
_token,
address(poolToken),
_amount,
exchangeFee,
_convertData
);
require(
amountReceived >= _expectedMinimumReceived,
"minimum swap amount not met"
);
holyPool.depositOnBehalfDirect(_beneficiary, amountReceived);
}
}
function withdrawFromPool(address _poolAddress, uint256 _amount) public {
withdrawFromPoolOnBehalf(msg.sender, _poolAddress, _amount);
}
function withdrawFromPoolOnBehalf(address _beneficiary, address _poolAddress, uint256 _amount) internal {
IHolyPoolV2 holyPool = IHolyPoolV2(_poolAddress);
IERC20 poolToken = IERC20(holyPool.getBaseAsset());
uint256 amountBefore = poolToken.balanceOf(address(this));
holyPool.withdraw(_beneficiary, _amount);
uint256 withdrawnAmount =
poolToken.balanceOf(address(this)).sub(amountBefore);
// if amount is less than expected, transfer anyway what was actually received
if (withdrawFee > 0) {
// process withdraw fees
uint256 feeAmount = withdrawnAmount.mul(withdrawFee).div(1e18);
poolToken.safeTransfer(_beneficiary, withdrawnAmount.sub(feeAmount));
} else {
poolToken.safeTransfer(_beneficiary, withdrawnAmount);
}
}
function setDepositFee(uint256 _depositFee) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
depositFee = _depositFee;
emit FeeChanged("deposit", _depositFee);
}
function setExchangeFee(uint256 _exchangeFee) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
exchangeFee = _exchangeFee;
emit FeeChanged("exchange", _exchangeFee);
}
function setWithdrawFee(uint256 _withdrawFee) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
withdrawFee = _withdrawFee;
emit FeeChanged("withdraw", _withdrawFee);
}
function setTransferFee(uint256 _transferFee) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
transferFee = _transferFee;
emit FeeChanged("transfer", _transferFee);
}
// token swap function (could be with fees but also can be subsidized later)
// perform conversion through exhcnageProxy (HolyWing)
function executeSwap(
address _tokenFrom,
address _tokenTo,
uint256 _amountFrom,
uint256 _expectedMinimumReceived,
bytes memory _convertData
) public payable {
executeSwapOnBehalf(msg.sender, _tokenFrom, _tokenTo, _amountFrom, _expectedMinimumReceived, _convertData);
}
function executeSwapOnBehalf(
address _beneficiary,
address _tokenFrom,
address _tokenTo,
uint256 _amountFrom,
uint256 _expectedMinimumReceived,
bytes memory _convertData
) internal {
require(_tokenFrom != _tokenTo, "same tokens provided");
// swap with direct transfer to HolyWing and HolyWing would transfer swapped token (or ETH) back to msg.sender
if (_tokenFrom != ETH_TOKEN_ADDRESS) {
IERC20(_tokenFrom).safeTransferFrom(
_beneficiary,
address(exchangeProxyContract),
_amountFrom
);
}
uint256 amountReceived =
IHolyWingV2(address(exchangeProxyContract)).executeSwapDirect{value: msg.value}(
_beneficiary,
_tokenFrom,
_tokenTo,
_amountFrom,
exchangeFee,
_convertData
);
require(
amountReceived >= _expectedMinimumReceived,
"minimum swap amount not met"
);
}
// payable fallback to receive ETH when swapping to raw ETH
receive() external payable {}
// this function is similar to emergencyTransfer, but relates to yield distribution
// fees are not transferred immediately to save gas costs for user operations
// so they accumulate on this contract address and can be claimed by HolyRedeemer
// when appropriate. Anyway, no user funds should appear on this contract, it
// only performs transfers, so such function has great power, but should be safe
// It does not include approval, so may be used by HolyRedeemer to get fees from swaps
// in different small token amounts
function claimFees(address _token, uint256 _amount) public {
require(
msg.sender == yieldDistributorAddress,
"yield distributor only"
);
if (_token != ETH_TOKEN_ADDRESS) {
IERC20(_token).safeTransfer(msg.sender, _amount);
} else {
payable(msg.sender).sendValue(_amount);
}
}
// all contracts that do not hold funds have this emergency function if someone occasionally
// transfers ERC20 tokens directly to this contract
// callable only by owner
function emergencyTransfer(
address _token,
address _destination,
uint256 _amount
) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
if (_token != ETH_TOKEN_ADDRESS) {
IERC20(_token).safeTransfer(_destination, _amount);
} else {
payable(_destination).sendValue(_amount);
}
emit EmergencyTransfer(_token, _destination, _amount);
}
///////////////////////////////////////////////////////////////////////////
// V3 SMART TREASURY AND SUBSIDIZED TRANSACTIONS
///////////////////////////////////////////////////////////////////////////
// these should be callable only by trusted backend wallet
// so that only signed by account and validated actions get executed and proper bonus amount
// if spending bonus does not revert, account has enough bonus tokens
// this contract must have EXECUTOR_ROLE set in Smart Treasury contract to call this
bytes32 public constant TRUSTED_EXECUTION_ROLE = keccak256("TRUSTED_EXECUTION"); // trusted execution wallets
address smartTreasury;
address tokenMoveAddress;
address tokenMoveEthLPAddress;
// if greater than zero, this is a fractional amount (1e18 = 1.0) fee applied to transfer operations (that could also be subsidized)
uint256 public transferFee;
// connect to Smart Treasury contract
function setSmartTreasury(address _smartTreasury) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
smartTreasury = _smartTreasury;
}
function setTreasuryTokens(address _tokenMoveAddress, address _tokenMoveEthLPAddress) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
tokenMoveAddress = _tokenMoveAddress;
tokenMoveEthLPAddress = _tokenMoveEthLPAddress;
}
// depositing to ST not requiring allowance to ST for MOVE or MOVE-ETH LP
function depositToTreasury(uint _tokenMoveAmount, uint _tokenMoveEthAmount) public {
if (_tokenMoveAmount > 0) {
IERC20(tokenMoveAddress).safeTransferFrom(msg.sender, smartTreasury, _tokenMoveAmount);
}
if (_tokenMoveEthAmount > 0) {
IERC20(tokenMoveEthLPAddress).safeTransferFrom(msg.sender, smartTreasury, _tokenMoveEthAmount);
}
ISmartTreasury(smartTreasury).depositOnBehalf(msg.sender, _tokenMoveAmount, _tokenMoveEthAmount);
}
// burn of MOVE tokens not requiring allowance so ST for MOVE
function claimAndBurn(uint _amount) public {
// burn bonus portion and send USDC
ISmartTreasury(smartTreasury).claimAndBurnOnBehalf(msg.sender, _amount);
// burn MOVE tokens (after USDC calculation and transfer complete to have proper totalSupply)
IBurnable(tokenMoveAddress).burnFrom(msg.sender, _amount);
}
// subsidized sending of ERC20 token to another address
function executeSendOnBehalf(address _beneficiary, address _token, address _destination, uint256 _amount, uint256 _bonus) public {
require(hasRole(TRUSTED_EXECUTION_ROLE, msg.sender), "trusted executor only");
ISmartTreasury(smartTreasury).spendBonus(_beneficiary, priceCorrection(_bonus));
// perform transfer, assuming this contract has allowance
if (transferFee == 0) {
IERC20(_token).safeTransferFrom(_beneficiary, _destination, _amount);
} else {
uint256 feeAmount = _amount.mul(transferFee).div(1e18);
IERC20(_token).safeTransferFrom(_beneficiary, address(this), _amount);
IERC20(_token).safeTransfer(_destination, _amount.sub(feeAmount));
}
}
// subsidized deposit of assets to pool
function executeDepositOnBehalf(address _beneficiary, address _token, address _pool, uint256 _amount, uint256 _expectedMinimumReceived, bytes memory _convertData, uint256 _bonus) public {
require(hasRole(TRUSTED_EXECUTION_ROLE, msg.sender), "trusted executor only");
ISmartTreasury(smartTreasury).spendBonus(_beneficiary, priceCorrection(_bonus));
// perform deposit, assuming this contract has allowance
// TODO: check deposit on behalf with raw Eth! it's not supported but that it reverts;
// TODO: check if swap would be executed properly;
depositToPoolOnBehalf(_beneficiary, _pool, _token, _amount, _expectedMinimumReceived, _convertData);
}
// subsidized withdraw of assets from pool
function executeWithdrawOnBehalf(address _beneficiary, address _pool, uint256 _amount, uint256 _bonus) public {
require(hasRole(TRUSTED_EXECUTION_ROLE, msg.sender), "trusted executor only");
ISmartTreasury(smartTreasury).spendBonus(_beneficiary, priceCorrection(_bonus));
withdrawFromPoolOnBehalf(_beneficiary, _pool, _amount);
}
// subsidized swap of ERC20 assets (also possible swap to raw Eth)
function executeSwapOnBehalf(address _beneficiary, address _tokenFrom, address _tokenTo, uint256 _amountFrom, uint256 _expectedMinimumReceived, bytes memory _convertData, uint256 _bonus) public {
require(hasRole(TRUSTED_EXECUTION_ROLE, msg.sender), "trusted executor only");
ISmartTreasury(smartTreasury).spendBonus(_beneficiary, priceCorrection(_bonus));
// TODO: check deposit on behalf with raw Eth! it's not supported but that it reverts;
executeSwapOnBehalf(_beneficiary, _tokenFrom, _tokenTo, _amountFrom, _expectedMinimumReceived, _convertData);
}
///////////////////////////////////////////////////////////////////////////
// V4 UPDATES
///////////////////////////////////////////////////////////////////////////
// Address of USDC/USD pricefeed from Chainlink
// (used for burning bonuses, USD amount expected)
address private USDCUSD_FEED_ADDRESS;
// if address is set to 0x, recalculation using pricefeed is disabled
function setUSDCPriceFeed(address _feed) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
USDCUSD_FEED_ADDRESS = _feed;
}
// if feed check is active, recalculate amount of bonus spent in USDC
// (_bonus amount is calculated from Eth price and is in USD)
function priceCorrection(uint256 _bonus) internal view returns(uint256) {
if (USDCUSD_FEED_ADDRESS != address(0)) {
// feed is providing values as 0.998 (1e8) means USDC is 0.998 USD, so USDC amount = USD amount / feed value
return _bonus.mul(1e8).div(uint256(IChainLinkFeed(USDCUSD_FEED_ADDRESS).latestAnswer()));
}
return _bonus;
}
///////////////////////////////////////////////////////////////////////////
// V5 UPDATES
///////////////////////////////////////////////////////////////////////////
event CardTopup(address indexed account, address token, uint256 valueToken, uint256 valueUSDC);
address private CARD_PARTNER_ADDRESS;
address private CARD_TOPUP_TOKEN;
function setCardPartnerAddress(address _addr) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
CARD_PARTNER_ADDRESS = _addr;
}
function setCardTopupToken(address _addr) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
CARD_TOPUP_TOKEN = _addr;
}
function cardTopUp(
address _beneficiary,
address _token,
uint256 _amount,
uint256 _expectedMinimumReceived,
bytes memory _convertData
) public payable {
if (CARD_TOPUP_TOKEN == _token) {
// no conversion is needed, allowance and balance checks performed in ERC20 token
// and not here to not waste any gas fees
IERC20(_token).safeTransferFrom(
_beneficiary,
CARD_PARTNER_ADDRESS,
_amount
);
emit CardTopup(_beneficiary, _token, _amount, _amount);
return;
}
// conversion is required, perform swap through exchangeProxy (HolyWing)
if (_token != ETH_TOKEN_ADDRESS) {
IERC20(_token).safeTransferFrom(
_beneficiary,
address(exchangeProxyContract),
_amount
);
}
// swap directly to partner address
uint256 amountReceived =
IHolyWingV2(address(exchangeProxyContract)).executeSwapDirect{value: msg.value}(
CARD_PARTNER_ADDRESS,
_token,
CARD_TOPUP_TOKEN,
_amount,
exchangeFee,
_convertData
);
require(
amountReceived >= _expectedMinimumReceived,
"minimum swap amount not met"
);
emit CardTopup(_beneficiary, _token, _amount, amountReceived);
}
} | this function exists due to OpenZeppelin quirks in safe allowance-changing methods we don't want to set allowance by small chunks as it would cost more gas for users and we don't want to set it to zero and then back to value (this makes no sense security-wise in single tx) from the other side, using it through safeIncreaseAllowance could revery due to SafeMath overflow Therefore, we calculate what amount we can increase allowance on to refill it to max uint256 value | abstract contract SafeAllowanceReset {
using SafeMath for uint256;
using SafeERC20 for IERC20;
function resetAllowanceIfNeeded(IERC20 _token, address _spender, uint256 _amount) internal {
uint256 allowance = _token.allowance(address(this), _spender);
if (allowance < _amount) {
uint256 newAllowance = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
IERC20(_token).safeIncreaseAllowance(address(_spender), newAllowance.sub(allowance));
}
}
function resetAllowanceIfNeeded(IERC20 _token, address _spender, uint256 _amount) internal {
uint256 allowance = _token.allowance(address(this), _spender);
if (allowance < _amount) {
uint256 newAllowance = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
IERC20(_token).safeIncreaseAllowance(address(_spender), newAllowance.sub(allowance));
}
}
}
| 1,975,431 | [
1,
2211,
445,
1704,
6541,
358,
3502,
62,
881,
84,
292,
267,
719,
31926,
316,
4183,
1699,
1359,
17,
343,
18183,
2590,
732,
2727,
1404,
2545,
358,
444,
1699,
1359,
635,
5264,
6055,
487,
518,
4102,
6991,
1898,
16189,
364,
3677,
471,
732,
2727,
1404,
2545,
358,
444,
518,
358,
3634,
471,
1508,
1473,
358,
460,
261,
2211,
7297,
1158,
12764,
4373,
17,
2460,
316,
2202,
2229,
13,
628,
326,
1308,
4889,
16,
1450,
518,
3059,
4183,
382,
11908,
7009,
1359,
3377,
283,
3242,
6541,
358,
14060,
10477,
9391,
17189,
16,
732,
4604,
4121,
3844,
732,
848,
10929,
1699,
1359,
603,
358,
1278,
737,
518,
358,
943,
2254,
5034,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
17801,
6835,
14060,
7009,
1359,
7013,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
225,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
225,
445,
2715,
7009,
1359,
18299,
12,
45,
654,
39,
3462,
389,
2316,
16,
1758,
389,
87,
1302,
264,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
565,
2254,
5034,
1699,
1359,
273,
389,
2316,
18,
5965,
1359,
12,
2867,
12,
2211,
3631,
389,
87,
1302,
264,
1769,
203,
565,
309,
261,
5965,
1359,
411,
389,
8949,
13,
288,
203,
1377,
2254,
5034,
394,
7009,
1359,
273,
374,
5297,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
18217,
31,
203,
1377,
467,
654,
39,
3462,
24899,
2316,
2934,
4626,
382,
11908,
7009,
1359,
12,
2867,
24899,
87,
1302,
264,
3631,
394,
7009,
1359,
18,
1717,
12,
5965,
1359,
10019,
203,
565,
289,
203,
225,
289,
203,
225,
445,
2715,
7009,
1359,
18299,
12,
45,
654,
39,
3462,
389,
2316,
16,
1758,
389,
87,
1302,
264,
16,
2254,
5034,
389,
8949,
13,
2713,
288,
203,
565,
2254,
5034,
1699,
1359,
273,
389,
2316,
18,
5965,
1359,
12,
2867,
12,
2211,
3631,
389,
87,
1302,
264,
1769,
203,
565,
309,
261,
5965,
1359,
411,
389,
8949,
13,
288,
203,
1377,
2254,
5034,
394,
7009,
1359,
273,
374,
5297,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
9460,
18217,
31,
203,
1377,
467,
654,
39,
3462,
24899,
2316,
2934,
4626,
382,
11908,
7009,
1359,
2
] |
// 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;
}
}
//
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
//
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
//
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
//
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
//
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
//
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
//
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
//
/**
* @dev Implementation of the {IERC777} 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}.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*/
contract ERC777 is Context, IERC777, IERC20 {
using SafeMath for uint256;
using Address for address;
IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] private _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) private _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) private _operators;
mapping(address => mapping(address => bool)) private _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) private _allowances;
/**
* @dev `defaultOperators` may be an empty array.
*/
constructor(
string memory name,
string memory symbol,
address[] memory defaultOperators
) public {
_name = name;
_symbol = symbol;
_defaultOperatorsArray = defaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this));
_ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this));
}
/**
* @dev See {IERC777-name}.
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public pure returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view override returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view override(IERC20, IERC777) returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of tokens owned by an account (`tokenHolder`).
*/
function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) {
return _balances[tokenHolder];
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes memory data) public override {
_send(_msgSender(), recipient, amount, data, "", true);
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) public override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
address from = _msgSender();
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev See {IERC777-burn}.
*
* Also emits a {IERC20-Transfer} event for ERC20 compatibility.
*/
function burn(uint256 amount, bytes memory data) public override {
_burn(_msgSender(), amount, data, "");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(
address operator,
address tokenHolder
) public view override returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) public override {
require(_msgSender() != operator, "ERC777: authorizing self as operator");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[_msgSender()][operator];
} else {
_operators[_msgSender()][operator] = true;
}
emit AuthorizedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) public override {
require(operator != _msgSender(), "ERC777: revoking self as operator");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[_msgSender()][operator] = true;
} else {
delete _operators[_msgSender()][operator];
}
emit RevokedOperator(operator, _msgSender());
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view override returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {IERC20-Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
public override
{
require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder");
_send(sender, recipient, amount, data, operatorData, true);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Emits {Burned} and {IERC20-Transfer} events.
*/
function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override {
require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder");
_burn(account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view override returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) public override returns (bool) {
address holder = _msgSender();
_approve(holder, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) {
require(recipient != address(0), "ERC777: transfer to the zero address");
require(holder != address(0), "ERC777: transfer from the zero address");
address spender = _msgSender();
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `operator`, `data` and `operatorData`.
*
* See {IERC777Sender} and {IERC777Recipient}.
*
* Emits {Minted} and {IERC20-Transfer} events.
*
* Requirements
*
* - `account` cannot be the zero address.
* - if `account` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function _mint(
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal virtual
{
require(account != address(0), "ERC777: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, amount);
// Update state variables
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_callTokensReceived(operator, address(0), account, amount, userData, operatorData, true);
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _send(
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
internal
{
require(from != address(0), "ERC777: send from the zero address");
require(to != address(0), "ERC777: send to the zero address");
address operator = _msgSender();
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck);
}
/**
* @dev Burn tokens
* @param from address token holder address
* @param amount uint256 amount of tokens to burn
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _burn(
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
internal virtual
{
require(from != address(0), "ERC777: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), amount);
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
// Update state variables
_balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Burned(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_beforeTokenTransfer(operator, from, to, amount);
_balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance");
_balances[to] = _balances[to].add(amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* @dev See {ERC20-_approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function _approve(address holder, address spender, uint256 value) internal {
require(holder != address(0), "ERC777: approve from the zero address");
require(spender != address(0), "ERC777: approve to the zero address");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient");
}
}
/**
* @dev Hook that is called before any token transfer. This includes
* calls to {send}, {transfer}, {operatorSend}, 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 operator, address from, address to, uint256 amount) internal virtual { }
}
//
// Created by [email protected]
contract TokenTimeLock is IERC777Recipient {
using SafeMath for uint256;
uint256 private constant THREEMONTH = 90 days;
// ERC777 basic token contract being held
IERC777 public token;
// admin work for lock
address private admin;
// lock info
mapping(address=>lockInfo) public balanceOf;
// release time
uint256 public releaseTime;
// token lock abount one locked account;
struct lockInfo{
uint256 amount;
uint256 balance;
uint256 lastReleaseTime;
}
constructor (IERC777 _token,uint256 _releaseTime) public {
// solhint-disable-next-line not-rely-on-time
require(_releaseTime > block.timestamp, "release time is before current time");
token = _token;
releaseTime = _releaseTime;
admin=msg.sender;
IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24)
.setInterfaceImplementer(
address(this),
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b,//keccak256("ERC777TokensRecipient")
address(this));
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release(address beneficiary) public {
require(beneficiary !=address(0),"beneficiary address is empty" );
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= releaseTime, "current time is before release time");
lockInfo storage info = balanceOf[beneficiary];
require(info.balance>0,"no tokens to release");
uint256 amount= info.amount.mul(10).div(100);//10%
if(amount>info.balance){
amount= info.balance;
}
require(token.balanceOf(address(this))>=amount,"no tokens to release" );
// solhint-disable-next-line not-rely-on-time
require(block.timestamp >= info.lastReleaseTime.add(THREEMONTH), "current time is before release time (three month)");
token.send(beneficiary, amount,"");
uint256 newBalance = info.balance.sub(amount);
if(newBalance==0){
delete balanceOf[beneficiary];//clear
return;
}
info.balance=newBalance;
// solhint-disable-next-line not-rely-on-time
info.lastReleaseTime=block.timestamp;
}
/**
@notice lock tokens to beneficiary;
*/
function lock(address beneficiary,uint256 amount) public{
require(msg.sender==admin,"msg.sender is not token address");
require(balanceOf[beneficiary].balance==0,"repeat lock");
// not check balance;
balanceOf[beneficiary] = lockInfo({
balance:amount,
amount:amount,lastReleaseTime:0 });
}
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) override public {
operator;from;to;amount;userData;operatorData;
require(msg.sender==address(token),"received token is not Token target");
}
}
//
// Created by [email protected]
contract Token is ERC777 {
TokenTimeLock public locker;
constructor() public ERC777("Business universal services Chain","BUS",new address[](0)) {
uint256 releaseTime= block.timestamp + 1095 days;// three years: 365*3
locker = new TokenTimeLock(this,releaseTime);
// 基金会5% 技术团队3% 机构12% 合计20%锁仓3年(36个月)
// 第37个月开始释放10%,每三个月释放一次,每次释放10%,两年半释放完毕
// 1 0xd5e7a36DA04C136B3a03beeAAE4E1Da8dC52a192 投资机构1 3% 300万枚
// 2 0xaEb3b44732E59e0F9B77316E1Df29be518F486bC 投资机构2 1.5% 150万枚
// 3 0xe9df36cF551bdbfE9CdFbbf2904f56A20D8B8dC1 投资机构3 2% 200万枚
// 4 0xB869C2903D3248F40f61773eb9Cf4c2cFf17a5d5 投资机构4 2.5% 250万枚
// 5 0x43401ae3ebcD9c6Ce252e9646373AA90DB588DCA 投资机构5 1% 100万枚
// 6 0x3b2Ac663c495A19aE2Fe1272B06e4f9d421Fe041 投资机构6 2% 200万枚
// 7 0x4dF5675fA8106296E73Dd7246C0d2fa51049117d 基金会 5% 500万枚
// 8 0xfea7d3dFA4625E9000D8DbaA0137d385CF699AFb 技术团队 3% 300万枚
// unlock
// 9 0x1Fa09e46492172ef5E8c99F870cc7a4958d5E41c DeFi 35% 3500万枚
// 10 0x4a204002d1AC965EB6A502DDB718834603553D4d 星际空间站 30% 3000万枚
// 11 0x85B51B91c072EA86BbD7290D68c43d8999381C67 跨链网关 10% 1000万枚
// 12 0x85A444ACFc0205c5eE6EaA4005074856bF1C2BF4 链上公益 5% 500万枚
// lock
_mint(address(locker),2000*10000*1e18,"","");
locker.lock(0xd5e7a36DA04C136B3a03beeAAE4E1Da8dC52a192,300*10000*1e18);
locker.lock(0xaEb3b44732E59e0F9B77316E1Df29be518F486bC,150*10000*1e18);
locker.lock(0xe9df36cF551bdbfE9CdFbbf2904f56A20D8B8dC1,200*10000*1e18);
locker.lock(0xB869C2903D3248F40f61773eb9Cf4c2cFf17a5d5,250*10000*1e18);
locker.lock(0x43401ae3ebcD9c6Ce252e9646373AA90DB588DCA,100*10000*1e18);
locker.lock(0x3b2Ac663c495A19aE2Fe1272B06e4f9d421Fe041,200*10000*1e18);
locker.lock(0x4dF5675fA8106296E73Dd7246C0d2fa51049117d,500*10000*1e18);
locker.lock(0xfea7d3dFA4625E9000D8DbaA0137d385CF699AFb,300*10000*1e18);
//unlock
_mint(0x1Fa09e46492172ef5E8c99F870cc7a4958d5E41c,3500*10000*1e18,"","");
_mint(0x4a204002d1AC965EB6A502DDB718834603553D4d,3000*10000*1e18,"","");
_mint(0x85B51B91c072EA86BbD7290D68c43d8999381C67,1000*10000*1e18,"","");
_mint(0x85A444ACFc0205c5eE6EaA4005074856bF1C2BF4,500*10000*1e18,"","");
}
} | * @notice Transfers tokens held by timelock to beneficiary./ solhint-disable-next-line not-rely-on-time | function release(address beneficiary) public {
require(beneficiary !=address(0),"beneficiary address is empty" );
require(block.timestamp >= releaseTime, "current time is before release time");
lockInfo storage info = balanceOf[beneficiary];
require(info.balance>0,"no tokens to release");
if(amount>info.balance){
amount= info.balance;
}
require(token.balanceOf(address(this))>=amount,"no tokens to release" );
token.send(beneficiary, amount,"");
uint256 newBalance = info.balance.sub(amount);
if(newBalance==0){
return;
}
info.balance=newBalance;
}
| 1,400,003 | [
1,
1429,
18881,
2430,
15770,
635,
1658,
292,
975,
358,
27641,
74,
14463,
814,
18,
19,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
486,
17,
266,
715,
17,
265,
17,
957,
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,
3992,
12,
2867,
27641,
74,
14463,
814,
13,
1071,
282,
288,
203,
3639,
2583,
12,
70,
4009,
74,
14463,
814,
480,
2867,
12,
20,
3631,
6,
70,
4009,
74,
14463,
814,
1758,
353,
1008,
6,
11272,
203,
203,
3639,
2583,
12,
2629,
18,
5508,
1545,
3992,
950,
16,
315,
2972,
813,
353,
1865,
3992,
813,
8863,
203,
203,
3639,
2176,
966,
2502,
1123,
273,
11013,
951,
63,
70,
4009,
74,
14463,
814,
15533,
203,
3639,
2583,
12,
1376,
18,
12296,
34,
20,
10837,
2135,
2430,
358,
3992,
8863,
203,
203,
3639,
309,
12,
8949,
34,
1376,
18,
12296,
15329,
203,
5411,
3844,
33,
1123,
18,
12296,
31,
203,
3639,
289,
203,
3639,
2583,
12,
2316,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
34,
33,
8949,
10837,
2135,
2430,
358,
3992,
6,
11272,
203,
203,
3639,
1147,
18,
4661,
12,
70,
4009,
74,
14463,
814,
16,
3844,
16,
3660,
1769,
203,
3639,
2254,
5034,
394,
13937,
273,
1123,
18,
12296,
18,
1717,
12,
8949,
1769,
203,
3639,
309,
12,
2704,
13937,
631,
20,
15329,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
1123,
18,
12296,
33,
2704,
13937,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./UhiveToken.sol";
contract UhiveVest {
// The token being sold
UhiveToken internal _token;
// Owner of this contract
address _owner;
uint256 internal _releaseDate;
function releaseDate() public view virtual returns (uint256) {
return _releaseDate;
}
function owner() public view virtual returns (address) {
return _owner;
}
function token() public view virtual returns (UhiveToken) {
return _token;
}
// Functions with this modifier can only be executed when the vesting period elapses
modifier onlyWhenReleased {
require(block.timestamp >= _releaseDate, "UhiveVest: Not ready for release...");
_;
}
// Functions with this modifier can only be executed by the owner
modifier onlyOwner() {
require(msg.sender == _owner, "UhiveVest: Method only allowed for contract owner..");
_;
}
constructor(address token_address_, uint256 releaseDate_){
_token = UhiveToken(token_address_);
_owner = msg.sender;
_releaseDate = releaseDate_;
}
function extendVestingPeriod(uint256 newReleaseDate_) onlyOwner public {
require(_releaseDate < newReleaseDate_, "UhiveVest: New date is before current release date...");
_releaseDate = newReleaseDate_;
}
/**
* Event for token transfer logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenTransfer(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
//Transfer tokens to a specified address, works only after vesting period elapses
function forwardTokens(address _beneficiary, uint256 amount) onlyOwner onlyWhenReleased public {
_preValidateTokenTransfer(_beneficiary, amount);
_deliverTokens(_beneficiary, amount);
}
//Withdraw tokens to owner wallet, works only after vesting period elapses
function withdrawTokens() onlyOwner onlyWhenReleased public {
uint256 vested = _token.balanceOf(address(this));
require(vested > 0, "UhiveVest: Vested amount = 0...");
_deliverTokens(_owner, vested);
}
//Change the owner wallet address
function changeOwner(address _newOwner) onlyOwner public {
require(_newOwner != address(0), "UhiveVest: Invalid owner address..");
_owner = _newOwner;
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
//Assertain the validity of the transfer
function _preValidateTokenTransfer(address _beneficiary, uint256 _tokenAmount) internal pure {
require(_beneficiary != address(0), "UhiveVest: Invalid beneficiary address...");
require(_tokenAmount > 0, "UhiveVest: Amount = 0...");
}
//Forward the tokens from the contract to the beneficiary
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
require(_token.transfer(_beneficiary, _tokenAmount) == true, "UhiveVest: Failed forwarding tokens");
emit TokenTransfer(msg.sender, _beneficiary, 0, _tokenAmount);
}
} | Assertain the validity of the transfer | function _preValidateTokenTransfer(address _beneficiary, uint256 _tokenAmount) internal pure {
require(_beneficiary != address(0), "UhiveVest: Invalid beneficiary address...");
require(_tokenAmount > 0, "UhiveVest: Amount = 0...");
}
| 12,009,691 | [
1,
8213,
530,
326,
13800,
434,
326,
7412,
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,
389,
1484,
4270,
1345,
5912,
12,
2867,
389,
70,
4009,
74,
14463,
814,
16,
2254,
5034,
389,
2316,
6275,
13,
2713,
16618,
288,
203,
3639,
2583,
24899,
70,
4009,
74,
14463,
814,
480,
1758,
12,
20,
3631,
315,
57,
76,
688,
58,
395,
30,
1962,
27641,
74,
14463,
814,
1758,
7070,
1769,
203,
3639,
2583,
24899,
2316,
6275,
405,
374,
16,
315,
57,
76,
688,
58,
395,
30,
16811,
273,
374,
7070,
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
] |
pragma solidity ^0.6.3;
contract RpcWithStorageTest {
uint256 current_counter;
uint256[] data;
event RpcEvent(
uint _someNumber
);
function get(uint256 _someId) public returns (uint256) {
return data[_someId];
}
function const() public returns (uint256) {
return 1;
}
function gas_increase_exponential() public {
// This function will use exponentially more storage. Useful to test
// high variation in gas for consecutive transactions
uint256 value;
uint256 i;
uint256 new_length = (5 + data.length) ** 2;
for (i=0; i < new_length - data.length ; i++) {
data.push(new_length);
}
emit RpcEvent(i);
}
function waste_storage(uint256 iterations) public {
uint256 i;
for (i=0; i<iterations; i++) {
data.push(i);
}
emit RpcEvent(i);
}
function next(uint256 next_counter, uint256 iterations) public {
assert(current_counter + 1 == next_counter);
uint256 i;
for (i=0; i<iterations; i++) {
data.push(i);
}
current_counter = next_counter;
}
}
| This function will use exponentially more storage. Useful to test high variation in gas for consecutive transactions | function gas_increase_exponential() public {
uint256 value;
uint256 i;
uint256 new_length = (5 + data.length) ** 2;
for (i=0; i < new_length - data.length ; i++) {
data.push(new_length);
}
emit RpcEvent(i);
}
| 6,486,201 | [
1,
2503,
445,
903,
999,
9100,
6261,
1898,
2502,
18,
19256,
358,
1842,
3551,
14761,
316,
16189,
364,
18221,
8938,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
16189,
67,
267,
11908,
67,
24045,
649,
1435,
1071,
288,
203,
3639,
2254,
5034,
460,
31,
203,
3639,
2254,
5034,
277,
31,
203,
3639,
2254,
5034,
394,
67,
2469,
273,
261,
25,
397,
501,
18,
2469,
13,
2826,
576,
31,
203,
3639,
364,
261,
77,
33,
20,
31,
277,
411,
394,
67,
2469,
300,
501,
18,
2469,
274,
277,
27245,
288,
203,
5411,
501,
18,
6206,
12,
2704,
67,
2469,
1769,
203,
3639,
289,
203,
203,
3639,
3626,
18564,
1133,
12,
77,
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
] |
pragma solidity >=0.5.0;
//Inheritance
import './interfaces/IStableCoinReserve.sol';
// Libraries
import "./libraries/SafeMath.sol";
// Internal references
import "./interfaces/IERC20.sol";
import "./interfaces/IAddressResolver.sol";
import "./interfaces/ISettings.sol";
import "./interfaces/IInsuranceFund.sol";
import "./interfaces/IInterestRewardsPoolEscrow.sol";
import "./interfaces/IStakingRewards.sol";
import "./interfaces/IUniswapV2Pair.sol";
import "./interfaces/IBaseUbeswapAdapter.sol";
contract StableCoinReserve is IStableCoinReserve {
using SafeMath for uint;
IAddressResolver public immutable ADDRESS_RESOLVER;
constructor(IAddressResolver _addressResolver) public {
ADDRESS_RESOLVER = _addressResolver;
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice Swaps cUSD for specified asset; meant to be called from an LToken contract
* @param asset Asset to swap to
* @param collateral Amount of cUSD to transfer from user
* @param borrowedAmount Amount of cUSD borrowed
* @param user Address of the user
* @return uint Number of asset tokens received
*/
function swapToAsset(address asset, uint collateral, uint borrowedAmount, address user) public override onlyLToken returns (uint) {
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
//Remove collateral from user
IERC20(stableCoinAddress).transferFrom(user, address(this), collateral);
require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(asset), "StableCoinReserve: currency not available");
require(IERC20(asset).balanceOf(address(this)) >= collateral.add(borrowedAmount), "StableCoinReserve: not enough cUSD available to swap");
uint numberOfDecimals = IERC20(asset).decimals();
uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(asset);
uint numberOfTokens = (collateral.add(borrowedAmount)).div(tokenToUSD).div(10 ** numberOfDecimals);
//Swap cUSD for asset
IERC20(stableCoinAddress).transfer(baseUbeswapAdapterAddress, collateral.add(borrowedAmount));
uint numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(stableCoinAddress, asset, collateral.add(borrowedAmount), numberOfTokens);
return numberOfTokensReceived;
}
/**
* @notice Swaps specified asset for cUSD; meant to be called from an LToken contract
* @param asset Asset to swap from
* @param userShare User's ratio of received tokens
* @param poolShare Pool's ratio of received tokens
* @param numberOfAssetTokens Number of asset tokens to swap
* @param user Address of the user
* @return uint Amount of cUSD user received
*/
function swapFromAsset(address asset, uint userShare, uint poolShare, uint numberOfAssetTokens, address user) public override onlyLToken returns (uint) {
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address insuranceFundAddress = ADDRESS_RESOLVER.getContractAddress("InsuranceFund");
address baseTradegenAddress = ADDRESS_RESOLVER.getContractAddress("BaseTradegen");
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(asset), "StableCoinReserve: currency not available");
//Get price of asset
uint numberOfDecimals = IERC20(asset).decimals();
uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(asset);
uint amountInUSD = (numberOfAssetTokens).mul(tokenToUSD).div(10 ** numberOfDecimals);
//Swap asset for cUSD
IERC20(asset).transfer(baseUbeswapAdapterAddress, numberOfAssetTokens);
uint cUSDReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(asset, stableCoinAddress, numberOfAssetTokens, amountInUSD);
//Transfer pool share to insurance fund if this contract's cUSD balance > totalVestedBalance (surplus if a withdrawal was made from insurance fund)
//Swap cUSD for TGEN if insurance fund's TGEN reserves are low
uint poolUSDAmount = cUSDReceived.mul(poolShare).div(userShare.add(poolShare));
uint surplus = (IERC20(stableCoinAddress).balanceOf(address(this)) > totalVestedBalance) ? poolUSDAmount.sub(IERC20(stableCoinAddress).balanceOf(address(this))) : 0;
if (IInsuranceFund(insuranceFundAddress).getFundStatus() < 2)
{
//Swap cUSD for TGEN and transfer to insurance fund
IERC20(stableCoinAddress).transfer(baseUbeswapAdapterAddress, surplus);
uint numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(stableCoinAddress, asset, surplus, 0);
IERC20(baseTradegenAddress).transfer(insuranceFundAddress, numberOfTokensReceived);
}
//Transfer cUSD to user
uint userUSDAmount = cUSDReceived.mul(userShare).div(userShare.add(poolShare));
IERC20(stableCoinAddress).transfer(user, userUSDAmount);
return userUSDAmount;
}
/**
* @notice Liquidates a leveraged asset; meant to be called from LeveragedAssetPositionManager contract
* @param asset Asset to swap from
* @param userShare User's ratio of received tokens
* @param liquidatorShare Liquidator's ratio of received tokens
* @param poolShare Pool's ration of received tokens
* @param numberOfAssetTokens Number of asset tokens to swap
* @param user Address of the user
* @param liquidator Address of the liquidator
* @return uint Amount of cUSD user received
*/
function liquidateLeveragedAsset(address asset, uint userShare, uint liquidatorShare, uint poolShare, uint numberOfAssetTokens, address user, address liquidator) public override onlyLToken returns (uint) {
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address insuranceFundAddress = ADDRESS_RESOLVER.getContractAddress("InsuranceFund");
address baseTradegenAddress = ADDRESS_RESOLVER.getContractAddress("BaseTradegen");
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(asset), "StableCoinStakingRewards: currency not available");
//Get price of asset
uint numberOfDecimals = IERC20(asset).decimals();
uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(asset);
uint amountInUSD = (numberOfAssetTokens).mul(tokenToUSD).div(10 ** numberOfDecimals);
//Swap asset for cUSD
IERC20(asset).transfer(baseUbeswapAdapterAddress, numberOfAssetTokens);
uint cUSDReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(asset, stableCoinAddress, numberOfAssetTokens, amountInUSD);
//Transfer pool share to insurance fund if this contract's cUSD balance > totalVestedBalance (surplus if a withdrawal was made from insurance fund)
//Swap cUSD for TGEN if insurance fund's TGEN reserves are low
uint poolUSDAmount = cUSDReceived.mul(poolShare).div(userShare.add(poolShare).add(liquidatorShare));
uint surplus = (IERC20(stableCoinAddress).balanceOf(address(this)) > totalVestedBalance) ? poolUSDAmount.sub(IERC20(stableCoinAddress).balanceOf(address(this))) : 0;
if (IInsuranceFund(insuranceFundAddress).getFundStatus() < 2)
{
//Swap cUSD for TGEN and transfer to insurance fund
IERC20(stableCoinAddress).transfer(baseUbeswapAdapterAddress, surplus);
uint numberOfTokensReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(stableCoinAddress, asset, surplus, 0);
IERC20(baseTradegenAddress).transfer(insuranceFundAddress, numberOfTokensReceived);
}
//Transfer cUSD to user
uint userUSDAmount = cUSDReceived.mul(userShare).div(userShare.add(poolShare).add(liquidatorShare));
IERC20(stableCoinAddress).transfer(user, userUSDAmount);
//Transfer cUSD to liquidator
uint liquidatorUSDAmount = cUSDReceived.mul(liquidatorShare).div(userShare.add(poolShare).add(liquidatorShare));
IERC20(stableCoinAddress).transfer(liquidator, liquidatorUSDAmount);
return userUSDAmount;
}
/**
* @notice Pays interest in the given asset; meant to be called from LeveragedAssetPositionManager contract
* @param asset Asset to swap from
* @param numberOfAssetTokens Number of asset tokens to swap
*/
function payInterest(address asset, uint numberOfAssetTokens) public override onlyLToken {
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address insuranceFundAddress = ADDRESS_RESOLVER.getContractAddress("InsuranceFund");
address interestRewardsPoolEscrowAddress = ADDRESS_RESOLVER.getContractAddress("InterestRewardsPoolEscrow");
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address stableCoinAddress = ISettings(settingsAddress).getStableCoinAddress();
require(ISettings(settingsAddress).checkIfCurrencyIsAvailable(asset), "StableCoinStakingRewards: currency not available");
//Get price of asset
uint numberOfDecimals = IERC20(asset).decimals();
uint tokenToUSD = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPrice(asset);
uint amountInUSD = (numberOfAssetTokens).mul(tokenToUSD).div(10 ** numberOfDecimals);
//Swap asset for cUSD
IERC20(asset).transfer(baseUbeswapAdapterAddress, numberOfAssetTokens);
uint cUSDReceived = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).swapFromStableCoinPool(asset, stableCoinAddress, numberOfAssetTokens, amountInUSD);
//Adjust distribution ratio based on status of insurance fund
uint insuranceFundAllocation;
uint insuranceFundStatus = IInsuranceFund(insuranceFundAddress).getFundStatus();
if (insuranceFundStatus == 0)
{
insuranceFundAllocation = 100;
}
else if (insuranceFundStatus == 1)
{
insuranceFundAllocation = 60;
}
else if (insuranceFundStatus == 2)
{
insuranceFundAllocation = 25;
}
else
{
insuranceFundAllocation = 0;
}
//Transfer received cUSD to insurance fund
IERC20(stableCoinAddress).transfer(insuranceFundAddress, cUSDReceived.mul(insuranceFundAllocation).div(100));
//Transfer received cUSD to interest rewards pool
IERC20(stableCoinAddress).transfer(interestRewardsPoolEscrowAddress, cUSDReceived.mul(100 - insuranceFundAllocation).div(100));
}
/**
* @notice Claims user's UBE rewards for leveraged yield farming
* @param user Address of the user
* @param amountOfUBE Amount of UBE to transfer to user
*/
function claimUserUBE(address user, uint amountOfUBE) public override onlyLToken {
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address UBE = ISettings(settingsAddress).getCurrencyKeyFromSymbol("UBE");
require(IERC20(UBE).balanceOf(address(this)) >= amountOfUBE, "StableCoinStakingRewards: not enough UBE in contract");
IERC20(UBE).transfer(user, amountOfUBE);
}
/**
* @notice Claims farm's UBE rewards for leveraged yield farming
* @notice Sends a small percentage of claimed UBE to user as a reward
* @param user Address of the user
* @param farmAddress Address of the farm
* @return (uint, uint) Amount of UBE claimed and keeper's share
*/
function claimFarmUBE(address user, address farmAddress) public override onlyLToken returns (uint, uint) {
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address settingsAddress = ADDRESS_RESOLVER.getContractAddress("Settings");
address UBE = ISettings(settingsAddress).getCurrencyKeyFromSymbol("UBE");
uint keeperReward = ISettings(settingsAddress).getParameterValue("UBEKeeperReward");
uint initialBalance = IERC20(UBE).balanceOf(address(this));
require(IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress) != address(0), "StableCoinStakingRewards: invalid farm address");
//Claim farm's available UBE
IStakingRewards(farmAddress).getReward();
//Transfer keeper reward to user
uint claimedUBE = IERC20(UBE).balanceOf(address(this)).sub(initialBalance);
IERC20(UBE).transfer(user, claimedUBE.mul(keeperReward).div(1000));
return (claimedUBE, claimedUBE.mul(keeperReward).div(1000));
}
/**
* @dev Adds liquidity for the two given tokens
* @param tokenA First token in pair
* @param tokenB Second token in pair
* @param amountA Amount of first token
* @param amountB Amount of second token
* @param farmAddress The token pair's farm address on Ubeswap
* @return Number of LP tokens received
*/
function addLiquidity(address tokenA, address tokenB, uint amountA, uint amountB, address farmAddress) public override onlyLToken returns (uint) {
require(tokenA != address(0), "StableCoinStakingRewards: invalid address for tokenA");
require(tokenB != address(0), "StableCoinStakingRewards: invalid address for tokenB");
require(amountA > 0, "StableCoinStakingRewards: amountA must be greater than 0");
require(amountB > 0, "StableCoinStakingRewards: amountB must be greater than 0");
require(IERC20(tokenA).balanceOf(address(this)) >= amountA, "StableCoinStakingRewards: not enough tokens invested in tokenA");
require(IERC20(tokenB).balanceOf(address(this)) >= amountB, "StableCoinStakingRewards: not enough tokens invested in tokenB");
//Check if farm exists for the token pair
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address stakingTokenAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress);
address pairAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).getPair(tokenA, tokenB);
require(stakingTokenAddress == pairAddress, "StableCoinStakingRewards: stakingTokenAddress does not match pairAddress");
//Add liquidity to Ubeswap pool and stake LP tokens into associated farm
uint numberOfLPTokens = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).addLiquidity(tokenA, tokenB, amountA, amountB);
IStakingRewards(stakingTokenAddress).stake(numberOfLPTokens);
return numberOfLPTokens;
}
/**
* @dev Removes liquidity for the two given tokens
* @param pair Address of liquidity pair
* @param farmAddress The token pair's farm address on Ubeswap
* @param numberOfLPTokens Number of LP tokens to remove
* @return (uint, uint) Amount of pair's token0 and token1 received
*/
function removeLiquidity(address pair, address farmAddress, uint numberOfLPTokens) public override onlyLToken returns (uint, uint) {
//Check if farm exists for the token pair
address baseUbeswapAdapterAddress = ADDRESS_RESOLVER.getContractAddress("BaseUbeswapAdapter");
address stakingTokenAddress = IBaseUbeswapAdapter(baseUbeswapAdapterAddress).checkIfFarmExists(farmAddress);
require(stakingTokenAddress == pair, "StableCoinStakingRewards: stakingTokenAddress does not match pair address");
//Withdraw LP tokens from farm
IStakingRewards(farmAddress).withdraw(numberOfLPTokens);
//Remove liquidity from Ubeswap liquidity pool
return IBaseUbeswapAdapter(baseUbeswapAdapterAddress).removeLiquidity(IUniswapV2Pair(pair).token0(), IUniswapV2Pair(pair).token1(), numberOfLPTokens);
}
/* ========== MODIFIERS ========== */
//TODO:
modifier onlyLToken() {
require(msg.sender == ADDRESS_RESOLVER.getContractAddress("LeveragedAssetPositionManager"), "StableCoinReserve: Only an LToken contract can call this function");
_;
}
} | Transfer received cUSD to interest rewards pool | IERC20(stableCoinAddress).transfer(interestRewardsPoolEscrowAddress, cUSDReceived.mul(100 - insuranceFundAllocation).div(100));
| 13,077,558 | [
1,
5912,
5079,
276,
3378,
40,
358,
16513,
283,
6397,
2845,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
467,
654,
39,
3462,
12,
15021,
27055,
1887,
2934,
13866,
12,
2761,
395,
17631,
14727,
2864,
6412,
492,
1887,
16,
276,
3378,
40,
8872,
18,
16411,
12,
6625,
300,
2763,
295,
1359,
42,
1074,
17353,
2934,
2892,
12,
6625,
10019,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/83/0xCFac462FDdaA0cC29Cd24Fa36243cA0e2Eefd5F4/sources/contracts/Upgradeable/BaseV1-bribesUpgradeable.sol | default snx staking contract implementation | contract BribeUpgradeable {
address public immutable _ve;
uint256 public constant PRECISION = 10**18;
mapping(address => uint256) public rewardRate;
mapping(address => uint256) public periodFinish;
mapping(address => uint256) public lastUpdateTime;
mapping(address => uint256) public rewardPerTokenStored;
mapping(address => mapping(uint256 => uint256)) public lastEarn;
mapping(address => mapping(uint256 => uint256))
public userRewardPerTokenStored;
address[] public rewards;
mapping(address => bool) public isReward;
uint256 public totalSupply;
mapping(uint256 => uint256) public balanceOf;
pragma solidity 0.8.11;
struct Checkpoint {
uint256 timestamp;
uint256 balanceOf;
}
struct RewardPerTokenCheckpoint {
uint256 timestamp;
uint256 rewardPerToken;
}
struct SupplyCheckpoint {
uint256 timestamp;
uint256 supply;
}
public rewardPerTokenCheckpoints;
event Deposit(address indexed from, uint256 tokenId, uint256 amount);
event Withdraw(address indexed from, uint256 tokenId, uint256 amount);
event NotifyReward(
address indexed from,
address indexed reward,
uint256 amount
);
event ClaimRewards(
address indexed from,
address indexed reward,
uint256 amount
);
mapping(uint256 => mapping(uint256 => Checkpoint)) public checkpoints;
mapping(uint256 => uint256) public numCheckpoints;
mapping(uint256 => SupplyCheckpoint) public supplyCheckpoints;
uint256 public supplyNumCheckpoints;
mapping(address => mapping(uint256 => RewardPerTokenCheckpoint))
mapping(address => uint256) public rewardPerTokenNumCheckpoints;
constructor(address _factory) {
factory = _factory;
_ve = IBaseV1Voter(_factory)._ve();
}
uint256 internal _unlocked = 1;
modifier lock() {
require(_unlocked == 1);
_unlocked = 2;
_;
_unlocked = 1;
}
function getPriorBalanceIndex(uint256 tokenId, uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = numCheckpoints[tokenId];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[tokenId][nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (checkpoints[tokenId][0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[tokenId][center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
function getPriorBalanceIndex(uint256 tokenId, uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = numCheckpoints[tokenId];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[tokenId][nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (checkpoints[tokenId][0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[tokenId][center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
function getPriorBalanceIndex(uint256 tokenId, uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = numCheckpoints[tokenId];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[tokenId][nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (checkpoints[tokenId][0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[tokenId][center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
function getPriorBalanceIndex(uint256 tokenId, uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = numCheckpoints[tokenId];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[tokenId][nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (checkpoints[tokenId][0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[tokenId][center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
function getPriorBalanceIndex(uint256 tokenId, uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = numCheckpoints[tokenId];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[tokenId][nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (checkpoints[tokenId][0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[tokenId][center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
function getPriorBalanceIndex(uint256 tokenId, uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = numCheckpoints[tokenId];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[tokenId][nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (checkpoints[tokenId][0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[tokenId][center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
} else if (cp.timestamp < timestamp) {
} else {
function getPriorSupplyIndex(uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = supplyNumCheckpoints;
if (nCheckpoints == 0) {
return 0;
}
if (supplyCheckpoints[nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (supplyCheckpoints[0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
SupplyCheckpoint memory cp = supplyCheckpoints[center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
function getPriorSupplyIndex(uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = supplyNumCheckpoints;
if (nCheckpoints == 0) {
return 0;
}
if (supplyCheckpoints[nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (supplyCheckpoints[0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
SupplyCheckpoint memory cp = supplyCheckpoints[center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
function getPriorSupplyIndex(uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = supplyNumCheckpoints;
if (nCheckpoints == 0) {
return 0;
}
if (supplyCheckpoints[nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (supplyCheckpoints[0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
SupplyCheckpoint memory cp = supplyCheckpoints[center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
function getPriorSupplyIndex(uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = supplyNumCheckpoints;
if (nCheckpoints == 0) {
return 0;
}
if (supplyCheckpoints[nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (supplyCheckpoints[0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
SupplyCheckpoint memory cp = supplyCheckpoints[center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
function getPriorSupplyIndex(uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = supplyNumCheckpoints;
if (nCheckpoints == 0) {
return 0;
}
if (supplyCheckpoints[nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (supplyCheckpoints[0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
SupplyCheckpoint memory cp = supplyCheckpoints[center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
function getPriorSupplyIndex(uint256 timestamp)
public
view
returns (uint256)
{
uint256 nCheckpoints = supplyNumCheckpoints;
if (nCheckpoints == 0) {
return 0;
}
if (supplyCheckpoints[nCheckpoints - 1].timestamp <= timestamp) {
return (nCheckpoints - 1);
}
if (supplyCheckpoints[0].timestamp > timestamp) {
return 0;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
SupplyCheckpoint memory cp = supplyCheckpoints[center];
if (cp.timestamp == timestamp) {
return center;
lower = center;
upper = center - 1;
}
}
return lower;
}
} else if (cp.timestamp < timestamp) {
} else {
function getPriorRewardPerToken(address token, uint256 timestamp)
public
view
returns (uint256, uint256)
{
uint256 nCheckpoints = rewardPerTokenNumCheckpoints[token];
if (nCheckpoints == 0) {
return (0, 0);
}
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp <=
timestamp
) {
return (
rewardPerTokenCheckpoints[token][nCheckpoints - 1]
.rewardPerToken,
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp
);
}
if (rewardPerTokenCheckpoints[token][0].timestamp > timestamp) {
return (0, 0);
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
RewardPerTokenCheckpoint memory cp = rewardPerTokenCheckpoints[
token
][center];
if (cp.timestamp == timestamp) {
return (cp.rewardPerToken, cp.timestamp);
lower = center;
upper = center - 1;
}
}
return (
rewardPerTokenCheckpoints[token][lower].rewardPerToken,
rewardPerTokenCheckpoints[token][lower].timestamp
);
}
function getPriorRewardPerToken(address token, uint256 timestamp)
public
view
returns (uint256, uint256)
{
uint256 nCheckpoints = rewardPerTokenNumCheckpoints[token];
if (nCheckpoints == 0) {
return (0, 0);
}
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp <=
timestamp
) {
return (
rewardPerTokenCheckpoints[token][nCheckpoints - 1]
.rewardPerToken,
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp
);
}
if (rewardPerTokenCheckpoints[token][0].timestamp > timestamp) {
return (0, 0);
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
RewardPerTokenCheckpoint memory cp = rewardPerTokenCheckpoints[
token
][center];
if (cp.timestamp == timestamp) {
return (cp.rewardPerToken, cp.timestamp);
lower = center;
upper = center - 1;
}
}
return (
rewardPerTokenCheckpoints[token][lower].rewardPerToken,
rewardPerTokenCheckpoints[token][lower].timestamp
);
}
if (
function getPriorRewardPerToken(address token, uint256 timestamp)
public
view
returns (uint256, uint256)
{
uint256 nCheckpoints = rewardPerTokenNumCheckpoints[token];
if (nCheckpoints == 0) {
return (0, 0);
}
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp <=
timestamp
) {
return (
rewardPerTokenCheckpoints[token][nCheckpoints - 1]
.rewardPerToken,
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp
);
}
if (rewardPerTokenCheckpoints[token][0].timestamp > timestamp) {
return (0, 0);
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
RewardPerTokenCheckpoint memory cp = rewardPerTokenCheckpoints[
token
][center];
if (cp.timestamp == timestamp) {
return (cp.rewardPerToken, cp.timestamp);
lower = center;
upper = center - 1;
}
}
return (
rewardPerTokenCheckpoints[token][lower].rewardPerToken,
rewardPerTokenCheckpoints[token][lower].timestamp
);
}
function getPriorRewardPerToken(address token, uint256 timestamp)
public
view
returns (uint256, uint256)
{
uint256 nCheckpoints = rewardPerTokenNumCheckpoints[token];
if (nCheckpoints == 0) {
return (0, 0);
}
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp <=
timestamp
) {
return (
rewardPerTokenCheckpoints[token][nCheckpoints - 1]
.rewardPerToken,
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp
);
}
if (rewardPerTokenCheckpoints[token][0].timestamp > timestamp) {
return (0, 0);
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
RewardPerTokenCheckpoint memory cp = rewardPerTokenCheckpoints[
token
][center];
if (cp.timestamp == timestamp) {
return (cp.rewardPerToken, cp.timestamp);
lower = center;
upper = center - 1;
}
}
return (
rewardPerTokenCheckpoints[token][lower].rewardPerToken,
rewardPerTokenCheckpoints[token][lower].timestamp
);
}
function getPriorRewardPerToken(address token, uint256 timestamp)
public
view
returns (uint256, uint256)
{
uint256 nCheckpoints = rewardPerTokenNumCheckpoints[token];
if (nCheckpoints == 0) {
return (0, 0);
}
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp <=
timestamp
) {
return (
rewardPerTokenCheckpoints[token][nCheckpoints - 1]
.rewardPerToken,
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp
);
}
if (rewardPerTokenCheckpoints[token][0].timestamp > timestamp) {
return (0, 0);
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
RewardPerTokenCheckpoint memory cp = rewardPerTokenCheckpoints[
token
][center];
if (cp.timestamp == timestamp) {
return (cp.rewardPerToken, cp.timestamp);
lower = center;
upper = center - 1;
}
}
return (
rewardPerTokenCheckpoints[token][lower].rewardPerToken,
rewardPerTokenCheckpoints[token][lower].timestamp
);
}
function getPriorRewardPerToken(address token, uint256 timestamp)
public
view
returns (uint256, uint256)
{
uint256 nCheckpoints = rewardPerTokenNumCheckpoints[token];
if (nCheckpoints == 0) {
return (0, 0);
}
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp <=
timestamp
) {
return (
rewardPerTokenCheckpoints[token][nCheckpoints - 1]
.rewardPerToken,
rewardPerTokenCheckpoints[token][nCheckpoints - 1].timestamp
);
}
if (rewardPerTokenCheckpoints[token][0].timestamp > timestamp) {
return (0, 0);
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
RewardPerTokenCheckpoint memory cp = rewardPerTokenCheckpoints[
token
][center];
if (cp.timestamp == timestamp) {
return (cp.rewardPerToken, cp.timestamp);
lower = center;
upper = center - 1;
}
}
return (
rewardPerTokenCheckpoints[token][lower].rewardPerToken,
rewardPerTokenCheckpoints[token][lower].timestamp
);
}
} else if (cp.timestamp < timestamp) {
} else {
function _writeCheckpoint(uint256 tokenId, uint256 balance) internal {
uint256 _timestamp = block.timestamp;
uint256 _nCheckPoints = numCheckpoints[tokenId];
if (
_nCheckPoints > 0 &&
checkpoints[tokenId][_nCheckPoints - 1].timestamp == _timestamp
) {
checkpoints[tokenId][_nCheckPoints - 1].balanceOf = balance;
checkpoints[tokenId][_nCheckPoints] = Checkpoint(
_timestamp,
balance
);
numCheckpoints[tokenId] = _nCheckPoints + 1;
}
}
function _writeCheckpoint(uint256 tokenId, uint256 balance) internal {
uint256 _timestamp = block.timestamp;
uint256 _nCheckPoints = numCheckpoints[tokenId];
if (
_nCheckPoints > 0 &&
checkpoints[tokenId][_nCheckPoints - 1].timestamp == _timestamp
) {
checkpoints[tokenId][_nCheckPoints - 1].balanceOf = balance;
checkpoints[tokenId][_nCheckPoints] = Checkpoint(
_timestamp,
balance
);
numCheckpoints[tokenId] = _nCheckPoints + 1;
}
}
} else {
function _writeRewardPerTokenCheckpoint(
address token,
uint256 reward,
uint256 timestamp
) internal {
uint256 _nCheckPoints = rewardPerTokenNumCheckpoints[token];
if (
_nCheckPoints > 0 &&
rewardPerTokenCheckpoints[token][_nCheckPoints - 1].timestamp ==
timestamp
) {
rewardPerTokenCheckpoints[token][_nCheckPoints - 1]
.rewardPerToken = reward;
rewardPerTokenCheckpoints[token][
_nCheckPoints
] = RewardPerTokenCheckpoint(timestamp, reward);
rewardPerTokenNumCheckpoints[token] = _nCheckPoints + 1;
}
}
function _writeRewardPerTokenCheckpoint(
address token,
uint256 reward,
uint256 timestamp
) internal {
uint256 _nCheckPoints = rewardPerTokenNumCheckpoints[token];
if (
_nCheckPoints > 0 &&
rewardPerTokenCheckpoints[token][_nCheckPoints - 1].timestamp ==
timestamp
) {
rewardPerTokenCheckpoints[token][_nCheckPoints - 1]
.rewardPerToken = reward;
rewardPerTokenCheckpoints[token][
_nCheckPoints
] = RewardPerTokenCheckpoint(timestamp, reward);
rewardPerTokenNumCheckpoints[token] = _nCheckPoints + 1;
}
}
} else {
function _writeSupplyCheckpoint() internal {
uint256 _nCheckPoints = supplyNumCheckpoints;
uint256 _timestamp = block.timestamp;
if (
_nCheckPoints > 0 &&
supplyCheckpoints[_nCheckPoints - 1].timestamp == _timestamp
) {
supplyCheckpoints[_nCheckPoints - 1].supply = totalSupply;
supplyCheckpoints[_nCheckPoints] = SupplyCheckpoint(
_timestamp,
totalSupply
);
supplyNumCheckpoints = _nCheckPoints + 1;
}
}
function _writeSupplyCheckpoint() internal {
uint256 _nCheckPoints = supplyNumCheckpoints;
uint256 _timestamp = block.timestamp;
if (
_nCheckPoints > 0 &&
supplyCheckpoints[_nCheckPoints - 1].timestamp == _timestamp
) {
supplyCheckpoints[_nCheckPoints - 1].supply = totalSupply;
supplyCheckpoints[_nCheckPoints] = SupplyCheckpoint(
_timestamp,
totalSupply
);
supplyNumCheckpoints = _nCheckPoints + 1;
}
}
} else {
function rewardsListLength() external view returns (uint256) {
return rewards.length;
}
function lastTimeRewardApplicable(address token)
public
view
returns (uint256)
{
return Math.min(block.timestamp, periodFinish[token]);
}
function getReward(uint256 tokenId, address[] memory tokens) external lock {
require(IVotingEscrow(_ve).isApprovedOrOwner(msg.sender, tokenId));
for (uint256 i = 0; i < tokens.length; i++) {
(
rewardPerTokenStored[tokens[i]],
lastUpdateTime[tokens[i]]
) = _updateRewardPerToken(tokens[i]);
uint256 _reward = earned(tokens[i], tokenId);
lastEarn[tokens[i]][tokenId] = block.timestamp;
userRewardPerTokenStored[tokens[i]][tokenId] = rewardPerTokenStored[
tokens[i]
];
if (_reward > 0) _safeTransfer(tokens[i], msg.sender, _reward);
emit ClaimRewards(msg.sender, tokens[i], _reward);
}
}
function getReward(uint256 tokenId, address[] memory tokens) external lock {
require(IVotingEscrow(_ve).isApprovedOrOwner(msg.sender, tokenId));
for (uint256 i = 0; i < tokens.length; i++) {
(
rewardPerTokenStored[tokens[i]],
lastUpdateTime[tokens[i]]
) = _updateRewardPerToken(tokens[i]);
uint256 _reward = earned(tokens[i], tokenId);
lastEarn[tokens[i]][tokenId] = block.timestamp;
userRewardPerTokenStored[tokens[i]][tokenId] = rewardPerTokenStored[
tokens[i]
];
if (_reward > 0) _safeTransfer(tokens[i], msg.sender, _reward);
emit ClaimRewards(msg.sender, tokens[i], _reward);
}
}
function getRewardForOwner(uint256 tokenId, address[] memory tokens)
external
lock
{
require(msg.sender == factory);
address _owner = IVotingEscrow(_ve).ownerOf(tokenId);
for (uint256 i = 0; i < tokens.length; i++) {
(
rewardPerTokenStored[tokens[i]],
lastUpdateTime[tokens[i]]
) = _updateRewardPerToken(tokens[i]);
uint256 _reward = earned(tokens[i], tokenId);
lastEarn[tokens[i]][tokenId] = block.timestamp;
userRewardPerTokenStored[tokens[i]][tokenId] = rewardPerTokenStored[
tokens[i]
];
if (_reward > 0) _safeTransfer(tokens[i], _owner, _reward);
emit ClaimRewards(_owner, tokens[i], _reward);
}
}
function getRewardForOwner(uint256 tokenId, address[] memory tokens)
external
lock
{
require(msg.sender == factory);
address _owner = IVotingEscrow(_ve).ownerOf(tokenId);
for (uint256 i = 0; i < tokens.length; i++) {
(
rewardPerTokenStored[tokens[i]],
lastUpdateTime[tokens[i]]
) = _updateRewardPerToken(tokens[i]);
uint256 _reward = earned(tokens[i], tokenId);
lastEarn[tokens[i]][tokenId] = block.timestamp;
userRewardPerTokenStored[tokens[i]][tokenId] = rewardPerTokenStored[
tokens[i]
];
if (_reward > 0) _safeTransfer(tokens[i], _owner, _reward);
emit ClaimRewards(_owner, tokens[i], _reward);
}
}
function rewardPerToken(address token) public view returns (uint256) {
if (totalSupply == 0) {
return rewardPerTokenStored[token];
}
return
rewardPerTokenStored[token] +
(((lastTimeRewardApplicable(token) -
Math.min(lastUpdateTime[token], periodFinish[token])) *
rewardRate[token] *
PRECISION) / totalSupply);
}
function rewardPerToken(address token) public view returns (uint256) {
if (totalSupply == 0) {
return rewardPerTokenStored[token];
}
return
rewardPerTokenStored[token] +
(((lastTimeRewardApplicable(token) -
Math.min(lastUpdateTime[token], periodFinish[token])) *
rewardRate[token] *
PRECISION) / totalSupply);
}
function batchRewardPerToken(address token, uint256 maxRuns) external {
(
rewardPerTokenStored[token],
lastUpdateTime[token]
) = _batchRewardPerToken(token, maxRuns);
}
function _batchRewardPerToken(address token, uint256 maxRuns)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = Math.min(supplyNumCheckpoints - 1, maxRuns);
for (uint256 i = _startIndex; i < _endIndex; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, endTime);
_startTimestamp = endTime;
}
}
return (reward, _startTimestamp);
}
function _batchRewardPerToken(address token, uint256 maxRuns)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = Math.min(supplyNumCheckpoints - 1, maxRuns);
for (uint256 i = _startIndex; i < _endIndex; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, endTime);
_startTimestamp = endTime;
}
}
return (reward, _startTimestamp);
}
function _batchRewardPerToken(address token, uint256 maxRuns)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = Math.min(supplyNumCheckpoints - 1, maxRuns);
for (uint256 i = _startIndex; i < _endIndex; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, endTime);
_startTimestamp = endTime;
}
}
return (reward, _startTimestamp);
}
function _batchRewardPerToken(address token, uint256 maxRuns)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = Math.min(supplyNumCheckpoints - 1, maxRuns);
for (uint256 i = _startIndex; i < _endIndex; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, endTime);
_startTimestamp = endTime;
}
}
return (reward, _startTimestamp);
}
function _batchRewardPerToken(address token, uint256 maxRuns)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = Math.min(supplyNumCheckpoints - 1, maxRuns);
for (uint256 i = _startIndex; i < _endIndex; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, endTime);
_startTimestamp = endTime;
}
}
return (reward, _startTimestamp);
}
function _calcRewardPerToken(
address token,
uint256 timestamp1,
uint256 timestamp0,
uint256 supply,
uint256 startTimestamp
) internal view returns (uint256, uint256) {
uint256 endTime = Math.max(timestamp1, startTimestamp);
return (
(((Math.min(endTime, periodFinish[token]) -
Math.min(
Math.max(timestamp0, startTimestamp),
periodFinish[token]
)) *
rewardRate[token] *
PRECISION) / supply),
endTime
);
}
function _updateRewardPerToken(address token)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = supplyNumCheckpoints - 1;
if (_endIndex - _startIndex > 1) {
for (uint256 i = _startIndex; i < _endIndex - 1; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 _endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, _endTime);
_startTimestamp = _endTime;
}
}
}
SupplyCheckpoint memory sp = supplyCheckpoints[_endIndex];
if (sp.supply > 0) {
(uint256 _reward, ) = _calcRewardPerToken(
token,
lastTimeRewardApplicable(token),
Math.max(sp.timestamp, _startTimestamp),
sp.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, block.timestamp);
_startTimestamp = block.timestamp;
}
return (reward, _startTimestamp);
}
function _updateRewardPerToken(address token)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = supplyNumCheckpoints - 1;
if (_endIndex - _startIndex > 1) {
for (uint256 i = _startIndex; i < _endIndex - 1; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 _endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, _endTime);
_startTimestamp = _endTime;
}
}
}
SupplyCheckpoint memory sp = supplyCheckpoints[_endIndex];
if (sp.supply > 0) {
(uint256 _reward, ) = _calcRewardPerToken(
token,
lastTimeRewardApplicable(token),
Math.max(sp.timestamp, _startTimestamp),
sp.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, block.timestamp);
_startTimestamp = block.timestamp;
}
return (reward, _startTimestamp);
}
function _updateRewardPerToken(address token)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = supplyNumCheckpoints - 1;
if (_endIndex - _startIndex > 1) {
for (uint256 i = _startIndex; i < _endIndex - 1; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 _endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, _endTime);
_startTimestamp = _endTime;
}
}
}
SupplyCheckpoint memory sp = supplyCheckpoints[_endIndex];
if (sp.supply > 0) {
(uint256 _reward, ) = _calcRewardPerToken(
token,
lastTimeRewardApplicable(token),
Math.max(sp.timestamp, _startTimestamp),
sp.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, block.timestamp);
_startTimestamp = block.timestamp;
}
return (reward, _startTimestamp);
}
function _updateRewardPerToken(address token)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = supplyNumCheckpoints - 1;
if (_endIndex - _startIndex > 1) {
for (uint256 i = _startIndex; i < _endIndex - 1; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 _endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, _endTime);
_startTimestamp = _endTime;
}
}
}
SupplyCheckpoint memory sp = supplyCheckpoints[_endIndex];
if (sp.supply > 0) {
(uint256 _reward, ) = _calcRewardPerToken(
token,
lastTimeRewardApplicable(token),
Math.max(sp.timestamp, _startTimestamp),
sp.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, block.timestamp);
_startTimestamp = block.timestamp;
}
return (reward, _startTimestamp);
}
function _updateRewardPerToken(address token)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = supplyNumCheckpoints - 1;
if (_endIndex - _startIndex > 1) {
for (uint256 i = _startIndex; i < _endIndex - 1; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 _endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, _endTime);
_startTimestamp = _endTime;
}
}
}
SupplyCheckpoint memory sp = supplyCheckpoints[_endIndex];
if (sp.supply > 0) {
(uint256 _reward, ) = _calcRewardPerToken(
token,
lastTimeRewardApplicable(token),
Math.max(sp.timestamp, _startTimestamp),
sp.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, block.timestamp);
_startTimestamp = block.timestamp;
}
return (reward, _startTimestamp);
}
function _updateRewardPerToken(address token)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = supplyNumCheckpoints - 1;
if (_endIndex - _startIndex > 1) {
for (uint256 i = _startIndex; i < _endIndex - 1; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 _endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, _endTime);
_startTimestamp = _endTime;
}
}
}
SupplyCheckpoint memory sp = supplyCheckpoints[_endIndex];
if (sp.supply > 0) {
(uint256 _reward, ) = _calcRewardPerToken(
token,
lastTimeRewardApplicable(token),
Math.max(sp.timestamp, _startTimestamp),
sp.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, block.timestamp);
_startTimestamp = block.timestamp;
}
return (reward, _startTimestamp);
}
function _updateRewardPerToken(address token)
internal
returns (uint256, uint256)
{
uint256 _startTimestamp = lastUpdateTime[token];
uint256 reward = rewardPerTokenStored[token];
if (supplyNumCheckpoints == 0) {
return (reward, _startTimestamp);
}
if (rewardRate[token] == 0) {
return (reward, block.timestamp);
}
uint256 _startIndex = getPriorSupplyIndex(_startTimestamp);
uint256 _endIndex = supplyNumCheckpoints - 1;
if (_endIndex - _startIndex > 1) {
for (uint256 i = _startIndex; i < _endIndex - 1; i++) {
SupplyCheckpoint memory sp0 = supplyCheckpoints[i];
if (sp0.supply > 0) {
SupplyCheckpoint memory sp1 = supplyCheckpoints[i + 1];
(uint256 _reward, uint256 _endTime) = _calcRewardPerToken(
token,
sp1.timestamp,
sp0.timestamp,
sp0.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, _endTime);
_startTimestamp = _endTime;
}
}
}
SupplyCheckpoint memory sp = supplyCheckpoints[_endIndex];
if (sp.supply > 0) {
(uint256 _reward, ) = _calcRewardPerToken(
token,
lastTimeRewardApplicable(token),
Math.max(sp.timestamp, _startTimestamp),
sp.supply,
_startTimestamp
);
reward += _reward;
_writeRewardPerTokenCheckpoint(token, reward, block.timestamp);
_startTimestamp = block.timestamp;
}
return (reward, _startTimestamp);
}
function earned(address token, uint256 tokenId)
public
view
returns (uint256)
{
uint256 _startTimestamp = Math.max(
lastEarn[token][tokenId],
rewardPerTokenCheckpoints[token][0].timestamp
);
if (numCheckpoints[tokenId] == 0) {
return 0;
}
uint256 _startIndex = getPriorBalanceIndex(tokenId, _startTimestamp);
uint256 _endIndex = numCheckpoints[tokenId] - 1;
uint256 reward = 0;
if (_endIndex - _startIndex > 1) {
for (uint256 i = _startIndex; i < _endIndex - 1; i++) {
Checkpoint memory cp0 = checkpoints[tokenId][i];
Checkpoint memory cp1 = checkpoints[tokenId][i + 1];
(uint256 _rewardPerTokenStored0, ) = getPriorRewardPerToken(
token,
cp0.timestamp
);
(uint256 _rewardPerTokenStored1, ) = getPriorRewardPerToken(
token,
cp1.timestamp
);
reward +=
(cp0.balanceOf *
(_rewardPerTokenStored1 - _rewardPerTokenStored0)) /
PRECISION;
}
}
Checkpoint memory cp = checkpoints[tokenId][_endIndex];
(uint256 _rewardPerTokenStored, ) = getPriorRewardPerToken(
token,
cp.timestamp
);
reward +=
(cp.balanceOf *
(rewardPerToken(token) -
Math.max(
_rewardPerTokenStored,
userRewardPerTokenStored[token][tokenId]
))) /
PRECISION;
return reward;
}
function earned(address token, uint256 tokenId)
public
view
returns (uint256)
{
uint256 _startTimestamp = Math.max(
lastEarn[token][tokenId],
rewardPerTokenCheckpoints[token][0].timestamp
);
if (numCheckpoints[tokenId] == 0) {
return 0;
}
uint256 _startIndex = getPriorBalanceIndex(tokenId, _startTimestamp);
uint256 _endIndex = numCheckpoints[tokenId] - 1;
uint256 reward = 0;
if (_endIndex - _startIndex > 1) {
for (uint256 i = _startIndex; i < _endIndex - 1; i++) {
Checkpoint memory cp0 = checkpoints[tokenId][i];
Checkpoint memory cp1 = checkpoints[tokenId][i + 1];
(uint256 _rewardPerTokenStored0, ) = getPriorRewardPerToken(
token,
cp0.timestamp
);
(uint256 _rewardPerTokenStored1, ) = getPriorRewardPerToken(
token,
cp1.timestamp
);
reward +=
(cp0.balanceOf *
(_rewardPerTokenStored1 - _rewardPerTokenStored0)) /
PRECISION;
}
}
Checkpoint memory cp = checkpoints[tokenId][_endIndex];
(uint256 _rewardPerTokenStored, ) = getPriorRewardPerToken(
token,
cp.timestamp
);
reward +=
(cp.balanceOf *
(rewardPerToken(token) -
Math.max(
_rewardPerTokenStored,
userRewardPerTokenStored[token][tokenId]
))) /
PRECISION;
return reward;
}
function earned(address token, uint256 tokenId)
public
view
returns (uint256)
{
uint256 _startTimestamp = Math.max(
lastEarn[token][tokenId],
rewardPerTokenCheckpoints[token][0].timestamp
);
if (numCheckpoints[tokenId] == 0) {
return 0;
}
uint256 _startIndex = getPriorBalanceIndex(tokenId, _startTimestamp);
uint256 _endIndex = numCheckpoints[tokenId] - 1;
uint256 reward = 0;
if (_endIndex - _startIndex > 1) {
for (uint256 i = _startIndex; i < _endIndex - 1; i++) {
Checkpoint memory cp0 = checkpoints[tokenId][i];
Checkpoint memory cp1 = checkpoints[tokenId][i + 1];
(uint256 _rewardPerTokenStored0, ) = getPriorRewardPerToken(
token,
cp0.timestamp
);
(uint256 _rewardPerTokenStored1, ) = getPriorRewardPerToken(
token,
cp1.timestamp
);
reward +=
(cp0.balanceOf *
(_rewardPerTokenStored1 - _rewardPerTokenStored0)) /
PRECISION;
}
}
Checkpoint memory cp = checkpoints[tokenId][_endIndex];
(uint256 _rewardPerTokenStored, ) = getPriorRewardPerToken(
token,
cp.timestamp
);
reward +=
(cp.balanceOf *
(rewardPerToken(token) -
Math.max(
_rewardPerTokenStored,
userRewardPerTokenStored[token][tokenId]
))) /
PRECISION;
return reward;
}
function earned(address token, uint256 tokenId)
public
view
returns (uint256)
{
uint256 _startTimestamp = Math.max(
lastEarn[token][tokenId],
rewardPerTokenCheckpoints[token][0].timestamp
);
if (numCheckpoints[tokenId] == 0) {
return 0;
}
uint256 _startIndex = getPriorBalanceIndex(tokenId, _startTimestamp);
uint256 _endIndex = numCheckpoints[tokenId] - 1;
uint256 reward = 0;
if (_endIndex - _startIndex > 1) {
for (uint256 i = _startIndex; i < _endIndex - 1; i++) {
Checkpoint memory cp0 = checkpoints[tokenId][i];
Checkpoint memory cp1 = checkpoints[tokenId][i + 1];
(uint256 _rewardPerTokenStored0, ) = getPriorRewardPerToken(
token,
cp0.timestamp
);
(uint256 _rewardPerTokenStored1, ) = getPriorRewardPerToken(
token,
cp1.timestamp
);
reward +=
(cp0.balanceOf *
(_rewardPerTokenStored1 - _rewardPerTokenStored0)) /
PRECISION;
}
}
Checkpoint memory cp = checkpoints[tokenId][_endIndex];
(uint256 _rewardPerTokenStored, ) = getPriorRewardPerToken(
token,
cp.timestamp
);
reward +=
(cp.balanceOf *
(rewardPerToken(token) -
Math.max(
_rewardPerTokenStored,
userRewardPerTokenStored[token][tokenId]
))) /
PRECISION;
return reward;
}
function _deposit(uint256 amount, uint256 tokenId) external {
require(msg.sender == factory);
totalSupply += amount;
balanceOf[tokenId] += amount;
_writeCheckpoint(tokenId, balanceOf[tokenId]);
_writeSupplyCheckpoint();
emit Deposit(msg.sender, tokenId, amount);
}
function _withdraw(uint256 amount, uint256 tokenId) external {
require(msg.sender == factory);
totalSupply -= amount;
balanceOf[tokenId] -= amount;
_writeCheckpoint(tokenId, balanceOf[tokenId]);
_writeSupplyCheckpoint();
emit Withdraw(msg.sender, tokenId, amount);
}
function left(address token) external view returns (uint256) {
if (block.timestamp >= periodFinish[token]) return 0;
uint256 _remaining = periodFinish[token] - block.timestamp;
return _remaining * rewardRate[token];
}
function notifyRewardAmount(address token, uint256 amount) external lock {
require(amount > 0);
if (rewardRate[token] == 0)
_writeRewardPerTokenCheckpoint(token, 0, block.timestamp);
(
rewardPerTokenStored[token],
lastUpdateTime[token]
) = _updateRewardPerToken(token);
if (block.timestamp >= periodFinish[token]) {
_safeTransferFrom(token, msg.sender, address(this), amount);
rewardRate[token] = amount / DURATION;
uint256 _remaining = periodFinish[token] - block.timestamp;
uint256 _left = _remaining * rewardRate[token];
require(amount > _left);
_safeTransferFrom(token, msg.sender, address(this), amount);
rewardRate[token] = (amount + _left) / DURATION;
}
require(rewardRate[token] > 0);
uint256 balance = IERC20(token).balanceOf(address(this));
require(
rewardRate[token] <= balance / DURATION,
"Provided reward too high"
);
periodFinish[token] = block.timestamp + DURATION;
if (!isReward[token]) {
isReward[token] = true;
rewards.push(token);
}
emit NotifyReward(msg.sender, token, amount);
}
function notifyRewardAmount(address token, uint256 amount) external lock {
require(amount > 0);
if (rewardRate[token] == 0)
_writeRewardPerTokenCheckpoint(token, 0, block.timestamp);
(
rewardPerTokenStored[token],
lastUpdateTime[token]
) = _updateRewardPerToken(token);
if (block.timestamp >= periodFinish[token]) {
_safeTransferFrom(token, msg.sender, address(this), amount);
rewardRate[token] = amount / DURATION;
uint256 _remaining = periodFinish[token] - block.timestamp;
uint256 _left = _remaining * rewardRate[token];
require(amount > _left);
_safeTransferFrom(token, msg.sender, address(this), amount);
rewardRate[token] = (amount + _left) / DURATION;
}
require(rewardRate[token] > 0);
uint256 balance = IERC20(token).balanceOf(address(this));
require(
rewardRate[token] <= balance / DURATION,
"Provided reward too high"
);
periodFinish[token] = block.timestamp + DURATION;
if (!isReward[token]) {
isReward[token] = true;
rewards.push(token);
}
emit NotifyReward(msg.sender, token, amount);
}
} else {
function notifyRewardAmount(address token, uint256 amount) external lock {
require(amount > 0);
if (rewardRate[token] == 0)
_writeRewardPerTokenCheckpoint(token, 0, block.timestamp);
(
rewardPerTokenStored[token],
lastUpdateTime[token]
) = _updateRewardPerToken(token);
if (block.timestamp >= periodFinish[token]) {
_safeTransferFrom(token, msg.sender, address(this), amount);
rewardRate[token] = amount / DURATION;
uint256 _remaining = periodFinish[token] - block.timestamp;
uint256 _left = _remaining * rewardRate[token];
require(amount > _left);
_safeTransferFrom(token, msg.sender, address(this), amount);
rewardRate[token] = (amount + _left) / DURATION;
}
require(rewardRate[token] > 0);
uint256 balance = IERC20(token).balanceOf(address(this));
require(
rewardRate[token] <= balance / DURATION,
"Provided reward too high"
);
periodFinish[token] = block.timestamp + DURATION;
if (!isReward[token]) {
isReward[token] = true;
rewards.push(token);
}
emit NotifyReward(msg.sender, token, amount);
}
function _safeTransfer(
address token,
address to,
uint256 value
) internal {
require(token.code.length > 0);
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(IERC20.transfer.selector, to, value)
);
require(success && (data.length == 0 || abi.decode(data, (bool))));
}
function _safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
require(token.code.length > 0);
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(
IERC20.transferFrom.selector,
from,
to,
value
)
);
require(success && (data.length == 0 || abi.decode(data, (bool))));
}
}
| 9,560,938 | [
1,
1886,
4556,
92,
384,
6159,
6835,
4471,
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,
605,
1902,
10784,
429,
288,
203,
565,
1758,
1071,
11732,
389,
537,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
7071,
26913,
273,
1728,
636,
2643,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
19890,
4727,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
3879,
11641,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
1142,
1891,
950,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
19890,
2173,
1345,
18005,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
2254,
5034,
3719,
1071,
1142,
41,
1303,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
11890,
5034,
516,
2254,
5034,
3719,
203,
3639,
1071,
729,
17631,
1060,
2173,
1345,
18005,
31,
203,
203,
565,
1758,
8526,
1071,
283,
6397,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
353,
17631,
1060,
31,
203,
203,
565,
2254,
5034,
1071,
2078,
3088,
1283,
31,
203,
565,
2874,
12,
11890,
5034,
516,
2254,
5034,
13,
1071,
11013,
951,
31,
203,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
2499,
31,
203,
565,
1958,
25569,
288,
203,
3639,
2254,
5034,
2858,
31,
203,
3639,
2254,
5034,
11013,
951,
31,
203,
565,
289,
203,
203,
565,
1958,
534,
359,
1060,
2173,
1345,
14431,
288,
203,
3639,
2254,
5034,
2858,
31,
203,
3639,
2254,
5034,
19890,
2173,
1345,
31,
203,
565,
289,
203,
203,
565,
1958,
3425,
1283,
14431,
288,
203,
3639,
2254,
5034,
2858,
31,
203,
3639,
2254,
5034,
14467,
2
] |
./full_match/1/0xA3DD98f92401899F9ba35F1a95c21AeeA57D73af/sources/contracts/RMRKWrappedEquippable.sol | * @notice Used to declare that the assets belonging to a given `equippableGroupId` are equippable into the `Slot` associated with the `partId` of the collection at the specified `parentAddress` @param equippableGroupId ID of the equippable group @param parentAddress Address of the parent into which the equippable group can be equipped into @param partId ID of the `Slot` that the items belonging to the equippable group can be equipped into/ | function setValidParentForEquippableGroup(
uint64 equippableGroupId,
address parentAddress,
uint64 partId
) public virtual onlyCollectionOwner {
_setValidParentForEquippableGroup(
equippableGroupId,
parentAddress,
partId
);
}
| 9,821,429 | [
1,
6668,
358,
14196,
716,
326,
7176,
17622,
358,
279,
864,
1375,
14298,
15491,
429,
8722,
68,
854,
1298,
15491,
429,
1368,
326,
1375,
8764,
68,
225,
3627,
598,
326,
1375,
2680,
548,
68,
434,
326,
1849,
622,
326,
1269,
1375,
2938,
1887,
68,
225,
1298,
15491,
429,
8722,
1599,
434,
326,
1298,
15491,
429,
1041,
225,
982,
1887,
5267,
434,
326,
982,
1368,
1492,
326,
1298,
15491,
429,
1041,
848,
506,
1298,
625,
1845,
1368,
225,
1087,
548,
1599,
434,
326,
1375,
8764,
68,
716,
326,
1516,
17622,
358,
326,
1298,
15491,
429,
1041,
848,
506,
1298,
625,
1845,
1368,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
444,
1556,
3054,
1290,
13142,
15491,
429,
1114,
12,
203,
3639,
2254,
1105,
1298,
15491,
429,
8722,
16,
203,
3639,
1758,
982,
1887,
16,
203,
3639,
2254,
1105,
1087,
548,
203,
565,
262,
1071,
5024,
1338,
2532,
5541,
288,
203,
3639,
389,
542,
1556,
3054,
1290,
13142,
15491,
429,
1114,
12,
203,
5411,
1298,
15491,
429,
8722,
16,
203,
5411,
982,
1887,
16,
203,
5411,
1087,
548,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x8348104A4583dfc075E6df8f8Bd98100aDc6bba4/sources/contracts/libs/BaseCollection.sol | * @dev Returns the interface ID of supports interfaces/ | function supportsInterface(
bytes4 interfaceId
) public view override(ERC721Enumerable, ERC2981) returns (bool) {
}
| 3,090,453 | [
1,
1356,
326,
1560,
1599,
434,
6146,
7349,
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
] | [
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,
6146,
1358,
12,
203,
3639,
1731,
24,
1560,
548,
203,
565,
262,
1071,
1476,
3849,
12,
654,
39,
27,
5340,
3572,
25121,
16,
4232,
39,
5540,
11861,
13,
1135,
261,
6430,
13,
288,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Copied from https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/v3.0.0/contracts/Initializable.sol
// Added public isInitialized() view of private initialized bool.
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
/**
* @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;
}
/**
* @dev Return true if and only if the contract has been initialized
* @return whether the contract has been initialized
*/
function isInitialized() public view returns (bool) {
return initialized;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {Context} from "Context.sol";
import {Initializable} from "Initializable.sol";
/**
* @title UpgradeableClaimable
* @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. Since
* this contract combines Claimable and UpgradableOwnable contracts, ownership
* can be later change via 2 step method {transferOwnership} and {claimOwnership}
*
* 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 UpgradeableClaimable is Initializable, Context {
address private _owner;
address private _pendingOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting a custom initial owner of choice.
* @param __owner Initial owner of contract to be set.
*/
function initialize(address __owner) internal initializer {
_owner = __owner;
emit OwnershipTransferred(address(0), __owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view returns (address) {
return _pendingOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == _pendingOwner, "Ownable: caller is not the pending owner");
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner {
emit OwnershipTransferred(_owner, _pendingOwner);
_owner = _pendingOwner;
_pendingOwner = address(0);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {UpgradeableClaimable as Claimable} from "UpgradeableClaimable.sol";
/**
* @title ImplementationReference
* @dev This contract is made to serve a simple purpose only.
* To hold the address of the implementation contract to be used by proxy.
* The implementation address, is changeable anytime by the owner of this contract.
*/
contract ImplementationReference is Claimable {
address public implementation;
/**
* @dev Event to show that implementation address has been changed
* @param newImplementation New address of the implementation
*/
event ImplementationChanged(address newImplementation);
/**
* @dev Set initial ownership and implementation address
* @param _implementation Initial address of the implementation
*/
constructor(address _implementation) public {
Claimable.initialize(msg.sender);
implementation = _implementation;
}
/**
* @dev Function to change the implementation address, which can be called only by the owner
* @param newImplementation New address of the implementation
*/
function setImplementation(address newImplementation) external onlyOwner {
implementation = newImplementation;
emit ImplementationChanged(newImplementation);
}
}
// SPDX-License-Identifier: MIT
// solhint-disable const-name-snakecase
pragma solidity 0.6.10;
import {ImplementationReference} from "ImplementationReference.sol";
/**
* @title OwnedProxyWithReference
* @dev This contract combines an upgradeability proxy with basic authorization control functionalities
* Its structure makes it easy for a group of contracts alike, to share an implementation and to change it easily for all of them at once
*/
contract OwnedProxyWithReference {
/**
* @dev Event to show ownership has been transferred
* @param previousOwner representing the address of the previous owner
* @param newOwner representing the address of the new owner
*/
event ProxyOwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Event to show ownership transfer is pending
* @param currentOwner representing the address of the current owner
* @param pendingOwner representing the address of the pending owner
*/
event NewPendingOwner(address currentOwner, address pendingOwner);
/**
* @dev Event to show implementation reference has been changed
* @param implementationReference address of the new implementation reference contract
*/
event ImplementationReferenceChanged(address implementationReference);
// Storage position of the owner and pendingOwner and implementationReference of the contract
// This is made to ensure, that memory spaces do not interfere with each other
bytes32 private constant proxyOwnerPosition = 0x6279e8199720cf3557ecd8b58d667c8edc486bd1cf3ad59ea9ebdfcae0d0dfac; //keccak256("trueUSD.proxy.owner");
bytes32 private constant pendingProxyOwnerPosition = 0x8ddbac328deee8d986ec3a7b933a196f96986cb4ee030d86cc56431c728b83f4; //keccak256("trueUSD.pending.proxy.owner");
bytes32 private constant implementationReferencePosition = keccak256("trueFiPool.implementation.reference"); //keccak256("trueFiPool.implementation.reference");
/**
* @dev the constructor sets the original owner of the contract to the sender account.
* @param _owner Initial owner of the proxy
* @param _implementationReference initial ImplementationReference address
*/
constructor(address _owner, address _implementationReference) public {
_setUpgradeabilityOwner(_owner);
_changeImplementationReference(_implementationReference);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyProxyOwner() {
require(msg.sender == proxyOwner(), "only Proxy Owner");
_;
}
/**
* @dev Throws if called by any account other than the pending owner.
*/
modifier onlyPendingProxyOwner() {
require(msg.sender == pendingProxyOwner(), "only pending Proxy Owner");
_;
}
/**
* @dev Tells the address of the owner
* @return owner the address of the owner
*/
function proxyOwner() public view returns (address owner) {
bytes32 position = proxyOwnerPosition;
assembly {
owner := sload(position)
}
}
/**
* @dev Tells the address of the owner
* @return pendingOwner the address of the pending owner
*/
function pendingProxyOwner() public view returns (address pendingOwner) {
bytes32 position = pendingProxyOwnerPosition;
assembly {
pendingOwner := sload(position)
}
}
/**
* @dev Sets the address of the owner
* @param newProxyOwner New owner to be set
*/
function _setUpgradeabilityOwner(address newProxyOwner) internal {
bytes32 position = proxyOwnerPosition;
assembly {
sstore(position, newProxyOwner)
}
}
/**
* @dev Sets the address of the owner
* @param newPendingProxyOwner New pending owner address
*/
function _setPendingUpgradeabilityOwner(address newPendingProxyOwner) internal {
bytes32 position = pendingProxyOwnerPosition;
assembly {
sstore(position, newPendingProxyOwner)
}
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* changes the pending owner to newOwner. But doesn't actually transfer
* @param newOwner The address to transfer ownership to.
*/
function transferProxyOwnership(address newOwner) external onlyProxyOwner {
require(newOwner != address(0));
_setPendingUpgradeabilityOwner(newOwner);
emit NewPendingOwner(proxyOwner(), newOwner);
}
/**
* @dev Allows the pendingOwner to claim ownership of the proxy
*/
function claimProxyOwnership() external onlyPendingProxyOwner {
emit ProxyOwnershipTransferred(proxyOwner(), pendingProxyOwner());
_setUpgradeabilityOwner(pendingProxyOwner());
_setPendingUpgradeabilityOwner(address(0));
}
/**
* @dev Allows the proxy owner to change the contract holding address of implementation.
* @param _implementationReference representing the address contract, which holds implementation.
*/
function changeImplementationReference(address _implementationReference) public virtual onlyProxyOwner {
_changeImplementationReference(_implementationReference);
}
/**
* @dev Get the address of current implementation.
* @return Returns address of implementation contract
*/
function implementation() public view returns (address) {
bytes32 position = implementationReferencePosition;
address implementationReference;
assembly {
implementationReference := sload(position)
}
return ImplementationReference(implementationReference).implementation();
}
/**
* @dev Fallback functions allowing to perform a delegatecall to the given implementation.
* This function will return whatever the implementation call returns
*/
fallback() external payable {
proxyCall();
}
/**
* @dev This fallback function gets called only when this contract is called without any calldata e.g. send(), transfer()
* This would also trigger receive() function on called implementation
*/
receive() external payable {
proxyCall();
}
/**
* @dev Performs a low level call, to the contract holding all the logic, changing state on this contract at the same time
*/
function proxyCall() internal {
address impl = implementation();
assembly {
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), impl, ptr, calldatasize(), 0, 0)
returndatacopy(ptr, 0, returndatasize())
switch result
case 0 {
revert(ptr, returndatasize())
}
default {
return(ptr, returndatasize())
}
}
}
/**
* @dev Function to internally change the contract holding address of implementation.
* @param _implementationReference representing the address contract, which holds implementation.
*/
function _changeImplementationReference(address _implementationReference) internal virtual {
bytes32 position = implementationReferencePosition;
assembly {
sstore(position, _implementationReference)
}
emit ImplementationReferenceChanged(address(_implementationReference));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {Address} from "Address.sol";
import {Context} from "Context.sol";
import {IERC20} from "IERC20.sol";
import {SafeMath} from "SafeMath.sol";
import {Initializable} from "Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 Initializable, 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.
*/
function __ERC20_initialize(string memory name, string memory symbol) internal initializer {
_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 virtual view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public virtual override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This 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 {}
function updateNameAndSymbol(string memory __name, string memory __symbol) internal {
_name = __name;
_symbol = __symbol;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
interface IPoolFactory {
function isPool(address pool) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {ITrueFiPool2} from "ITrueFiPool2.sol";
interface ITrueLender2 {
// @dev calculate overall value of the pools
function value(ITrueFiPool2 pool) external view returns (uint256);
// @dev distribute a basket of tokens for exiting user
function distribute(
address recipient,
uint256 numerator,
uint256 denominator
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20} from "IERC20.sol";
interface IERC20WithDecimals is IERC20 {
function decimals() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {IERC20WithDecimals} from "IERC20WithDecimals.sol";
/**
* @dev Oracle that converts any token to and from TRU
* Used for liquidations and valuing of liquidated TRU in the pool
*/
interface ITrueFiPoolOracle {
// token address
function token() external view returns (IERC20WithDecimals);
// amount of tokens 1 TRU is worth
function truToToken(uint256 truAmount) external view returns (uint256);
// amount of TRU 1 token is worth
function tokenToTru(uint256 tokenAmount) external view returns (uint256);
// USD price of token with 18 decimals
function tokenToUsd(uint256 tokenAmount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
pragma experimental ABIEncoderV2;
interface I1Inch3 {
struct SwapDescription {
address srcToken;
address dstToken;
address srcReceiver;
address dstReceiver;
uint256 amount;
uint256 minReturnAmount;
uint256 flags;
bytes permit;
}
function swap(
address caller,
SwapDescription calldata desc,
bytes calldata data
)
external
returns (
uint256 returnAmount,
uint256 gasLeft,
uint256 chiSpent
);
function unoswap(
address srcToken,
uint256 amount,
uint256 minReturn,
bytes32[] calldata /* pools */
) external payable returns (uint256 returnAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {ERC20, IERC20} from "UpgradeableERC20.sol";
import {ITrueLender2} from "ITrueLender2.sol";
import {ITrueFiPoolOracle} from "ITrueFiPoolOracle.sol";
import {I1Inch3} from "I1Inch3.sol";
interface ITrueFiPool2 is IERC20 {
function initialize(
ERC20 _token,
ERC20 _stakingToken,
ITrueLender2 _lender,
I1Inch3 __1Inch,
address __owner
) external;
function token() external view returns (ERC20);
function oracle() external view returns (ITrueFiPoolOracle);
/**
* @dev Join the pool by depositing tokens
* @param amount amount of tokens to deposit
*/
function join(uint256 amount) external;
/**
* @dev borrow from pool
* 1. Transfer TUSD to sender
* 2. Only lending pool should be allowed to call this
*/
function borrow(uint256 amount) external;
/**
* @dev pay borrowed money back to pool
* 1. Transfer TUSD from sender
* 2. Only lending pool should be allowed to call this
*/
function repay(uint256 currencyAmount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.10;
import {UpgradeableClaimable as Claimable} from "UpgradeableClaimable.sol";
import {OwnedProxyWithReference} from "OwnedProxyWithReference.sol";
import {ERC20, IERC20} from "UpgradeableERC20.sol";
import {IPoolFactory} from "IPoolFactory.sol";
import {ITrueFiPool2, I1Inch3} from "ITrueFiPool2.sol";
import {ITrueLender2} from "ITrueLender2.sol";
import {ImplementationReference} from "ImplementationReference.sol";
/**
* @title PoolFactory
* @dev Factory used to create pools for a chosen asset
* This contract creates a new pool and transfer its ownership to the governance contract
* Anyone can create a new pool, however the token has to be whitelisted
* Initially created pools hold the same implementation, which can be changed later on individually
*/
contract PoolFactory is IPoolFactory, Claimable {
// ================ WARNING ==================
// ===== THIS CONTRACT IS INITIALIZABLE ======
// === STORAGE VARIABLES ARE DECLARED BELOW ==
// REMOVAL OR REORDER OF VARIABLES WILL RESULT
// ========= IN STORAGE CORRUPTION ===========
// @dev Mapping of ERC20 token's addresses to its pool's addresses
mapping(address => address) public pool;
mapping(address => bool) public override isPool;
// @dev Whitelist for tokens, which can have pools created
mapping(address => bool) public isAllowed;
bool public allowAll;
ImplementationReference public poolImplementationReference;
ERC20 public liquidationToken;
ITrueLender2 public trueLender2;
// ======= STORAGE DECLARATION END ===========
I1Inch3 public constant ONE_INCH_ADDRESS = I1Inch3(0x11111112542D85B3EF69AE05771c2dCCff4fAa26);
/**
* @dev Event to show creation of the new pool
* @param token Address of token, for which the pool was created
* @param pool Address of new pool's proxy
*/
event PoolCreated(address token, address pool);
/**
* @dev Event to show that token is now allowed/disallowed to have a pool created
* @param token Address of token
* @param status New status of allowance
*/
event AllowedStatusChanged(address token, bool status);
/**
* @dev Event to show that allowAll status has been changed
* @param status New status of allowAll
*/
event AllowAllStatusChanged(bool status);
/**
* @dev Event to show that trueLender was changed
* @param trueLender2 New instance of ITrueLender2
*/
event TrueLenderChanged(ITrueLender2 trueLender2);
/**
* @dev Throws if token already has an existing corresponding pool
* @param token Token to be checked for existing pool
*/
modifier onlyNotExistingPools(address token) {
require(pool[token] == address(0), "PoolFactory: This token already has a corresponding pool");
_;
}
/**
* @dev Throws if token is not whitelisted for creating new pool
* @param token Address of token to be checked in whitelist
*/
modifier onlyAllowed(address token) {
require(allowAll || isAllowed[token], "PoolFactory: This token is not allowed to have a pool");
_;
}
/**
* @dev Initialize this contract with provided parameters
* @param _poolImplementationReference First implementation reference of TrueFiPool
*/
function initialize(
ImplementationReference _poolImplementationReference,
ERC20 _liquidationToken,
ITrueLender2 _trueLender2
) external initializer {
Claimable.initialize(msg.sender);
liquidationToken = _liquidationToken;
poolImplementationReference = _poolImplementationReference;
trueLender2 = _trueLender2;
}
/**
* @dev After TUSD pool is updated to comply with ITrueFiPool2 interface, call this with it's address
*/
function addLegacyPool(ITrueFiPool2 legacyPool) external onlyOwner {
pool[address(legacyPool.token())] = address(legacyPool);
isPool[address(legacyPool)] = true;
}
/**
* @dev Create a new pool behind proxy. Update new pool's implementation.
* Transfer ownership of created pool to Factory owner.
* @param token Address of token which the pool will correspond to.
*/
function createPool(address token) external onlyAllowed(token) onlyNotExistingPools(token) {
OwnedProxyWithReference proxy = new OwnedProxyWithReference(this.owner(), address(poolImplementationReference));
pool[token] = address(proxy);
isPool[address(proxy)] = true;
ITrueFiPool2(address(proxy)).initialize(ERC20(token), liquidationToken, trueLender2, ONE_INCH_ADDRESS, this.owner());
emit PoolCreated(token, address(proxy));
}
/**
* @dev Change token allowed status
* @param token Address of token to be allowed or disallowed
* @param status New status of allowance for token
*/
function whitelist(address token, bool status) external onlyOwner {
isAllowed[token] = status;
emit AllowedStatusChanged(token, status);
}
/**
* @dev Change allowAll status
* @param status New status of allowAll
*/
function setAllowAll(bool status) external onlyOwner {
allowAll = status;
emit AllowAllStatusChanged(status);
}
function setTrueLender(ITrueLender2 _trueLender2) external onlyOwner {
require(address(_trueLender2) != address(0), "PoolFactory: TrueLender address cannot be set to 0");
trueLender2 = _trueLender2;
emit TrueLenderChanged(trueLender2);
}
}
| * @dev Throws if token is not whitelisted for creating new pool @param token Address of token to be checked in whitelist/ | modifier onlyAllowed(address token) {
require(allowAll || isAllowed[token], "PoolFactory: This token is not allowed to have a pool");
_;
}
| 1,418,963 | [
1,
21845,
309,
1147,
353,
486,
26944,
364,
4979,
394,
2845,
225,
1147,
5267,
434,
1147,
358,
506,
5950,
316,
10734,
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,
565,
9606,
1338,
5042,
12,
2867,
1147,
13,
288,
203,
3639,
2583,
12,
5965,
1595,
747,
21956,
63,
2316,
6487,
315,
2864,
1733,
30,
1220,
1147,
353,
486,
2935,
358,
1240,
279,
2845,
8863,
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
] |
// contracts/HolyPassageV2.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library CountersUpgradeable {
using SafeMathUpgradeable for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// 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;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 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 ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
/*
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @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 returns (uint256) {
return _roles[role].members.length();
}
/**
* @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 returns (address) {
return _roles[role].members.at(index);
}
/**
* @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 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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_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 {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_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 {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
using SafeMathUpgradeable for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
uint256[50] private __gap;
}
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable {
function __ERC20Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauserUpgradeable is Initializable, ContextUpgradeable, AccessControlUpgradeable, ERC20BurnableUpgradeable, ERC20PausableUpgradeable {
function initialize(string memory name, string memory symbol) public virtual initializer {
__ERC20PresetMinterPauser_init(name, symbol);
}
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__ERC20PresetMinterPauser_init_unchained(name, symbol);
}
function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount);
}
uint256[50] private __gap;
}
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal initializer {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal initializer {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
uint256[50] private __gap;
}
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping (address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal initializer {
__Context_init_unchained();
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory name) internal initializer {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
amount,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = _recoverSigner(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, amount);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function _recoverSigner(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n Г· 2 + 1, and for v in (282): v в€€ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
uint256[49] private __gap;
}
/**
* @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);
}
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);
}
}
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev 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);
}
/**
* @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");
}
}
}
/*
"HH", "Holyheld", the Holyheld token contract
Properties used from OpenZeppelin:
ERC20PresetMinterPauserUpgradeable.sol -- preset for mintable, pausable, burnable ERC20 token
ERC20PermitUpgradeable.sol -- ported from drafts (test added) to implement permit()
*/
contract HHToken is ERC20PresetMinterPauserUpgradeable, ERC20PermitUpgradeable {
using SafeERC20 for IERC20;
// initializer is defined within preset
function initialize(string memory name, string memory symbol) public override initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__ERC20PresetMinterPauser_init_unchained(name, symbol);
__ERC20Permit_init(name);
}
function uniqueIdentifier() public pure returns(string memory) {
return "HolyheldToken";
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20PresetMinterPauserUpgradeable, ERC20Upgradeable) {
super._beforeTokenTransfer(from, to, amount);
}
// all contracts that do not hold funds have this emergency function if someone occasionally
// transfers ERC20 tokens directly to this contract
// callable only by owner
function emergencyTransfer(address _token, address _destination, uint256 _amount) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
IERC20(_token).safeTransfer(_destination, _amount);
}
}
// Interface to represent data fetch for bonus token claim
interface IHolyVisor {
function bonusInfo(address) external view returns(uint256, uint256);
function bonusTotalUnlocked() external view returns(uint256);
function bonusTotalTokens() external view returns(uint256);
}
/*
HolyPassage is a migration contract from HOLY token to HH token.
It is able to mint HH tokens accumulating HOLY tokens which are burned upon migration (transferred to 0x0...00 address)
The migration procedure includes following steps:
transaction 1:
- user approves spending of the HOLY token to the migrator contract (required one-time);
transaction 2:
- migrator contract burns HOLY tokens from user wallet;
- migrator mints exactly the same amount of HH tokens to user wallet;
- migrator increments the amount of tokens user has migrated (this is used to determine available bonus cap);
- if address has non-zero claimable bonus tokens, this amount is calculated and transferred too during migration call;
Additional conditions:
- migration is only available from 20 Jan 2021 to 28 Feb 2021, otherwise migration calls are declined;
Safety measures (could be called only by owner):
- freeze/unfreeze bonus program;
- freeze/unfreeze migration;
- change migration time window setMigrationWindow();
- change total bonus tokens amount (in HolyVisor setTotalAmount());
- change multiplier and cap amount for particular address (in HolyVisor setData());
All non-zero amounts of bonus tokens could be airdropped automatically on a weekly basis (to keep gas costs reasonable);
- this is function that can be called by anyone (but it could be very gas expensive)
airdropBonuses(address[]) -- addresses to check and airdrop bonus HH to (all addresses may not fit into one transaction);
*/
contract HolyPassageV3 is AccessControlUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//migration time window boundaries
uint256 public migrationStartTimestamp;
uint256 public migrationEndTimestamp;
//OpenZeppelin ERC20 implementation (if ERC20Burnable is not used) won't allow tokens to be sent to 0x0..0 address
//NOTE: place this address to something claimable to test migration in mainnet with real tokens
address private constant BURN_ADDRESS = 0x000000000000000000000000000000000000dEaD;
IERC20 public oldToken;
HHToken public newToken;
function initialize(address _oldToken, address _newToken) public initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
oldToken = IERC20(_oldToken);
newToken = HHToken(_newToken);
}
// data about amount migrated and claimed bonus for all users
mapping(address => uint256) public migratedTokens;
mapping(address => uint256) public claimedBonusTokens;
event Migrated(address indexed user, uint256 amount);
event ClaimedBonus(address indexed user, uint256 amount);
//HolyVisor is a contract that handles bonus multipliers data
IHolyVisor private holyVisor;
// enable/disable flags
bool public migrationEnabled;
bool public bonusClaimEnabled;
// migrate user HOLY tokens to HH tokens (without multipliers)
// allowance should be already provided to this contract address by user
function emergencyMigrate() public {
require(block.timestamp >= migrationStartTimestamp && block.timestamp < migrationEndTimestamp, "time not in migration window");
uint256 userBalance = oldToken.balanceOf(msg.sender);
uint256 contractAllowance = oldToken.allowance(msg.sender, address(this));
require(userBalance > 0, "no tokens to migrate");
require(contractAllowance >= userBalance, "insufficient allowance");
oldToken.safeTransferFrom(msg.sender, BURN_ADDRESS, userBalance); // burn old token
newToken.mint(msg.sender, userBalance); // mint new token to user address
migratedTokens[msg.sender] += userBalance;
emit Migrated(msg.sender, userBalance);
}
// migrate user HOLY tokens to HH tokens
// allowance should be already provided to this contract address by user
function migrate() public {
require(migrationEnabled, "migration disabled");
require(block.timestamp >= migrationStartTimestamp && block.timestamp < migrationEndTimestamp, "time not in migration window");
uint256 userBalance = oldToken.balanceOf(msg.sender);
uint256 contractAllowance = oldToken.allowance(msg.sender, address(this));
require(userBalance > 0, "no tokens to migrate");
require(contractAllowance >= userBalance, "insufficient allowance");
oldToken.safeTransferFrom(msg.sender, BURN_ADDRESS, userBalance); // burn old token
//don't call claimBonusForAddress() to save some gas and mint in one call
uint256 bonusAmount = getClaimableBonusIncludingMigration(msg.sender, userBalance);
uint256 totalAmount = userBalance + bonusAmount;
newToken.mint(msg.sender, totalAmount); // mint new token to user address
migratedTokens[msg.sender] += userBalance;
emit Migrated(msg.sender, userBalance);
if (bonusAmount > 0) {
emit ClaimedBonus(msg.sender, bonusAmount);
claimedBonusTokens[msg.sender] += bonusAmount;
}
}
// this function is similar to public getClaimableBonus but takes currently migrating amount into calculation
function getClaimableBonusIncludingMigration(address _account, uint256 _currentlyMigratingAmount) private view returns(uint256) {
if (!bonusClaimEnabled) {
return 0;
}
//go into HolyVisor and retrieve claimable bonus, take into account the amount is currently migrating
uint256 userMultiplier = 0;
uint256 userAmountCap = 0;
uint256 totalUnlocked = 0;
uint256 totalBonusAmount = 0;
if (address(holyVisor) != address(0)) {
(userMultiplier, userAmountCap) = holyVisor.bonusInfo(_account);
totalUnlocked = holyVisor.bonusTotalUnlocked();
totalBonusAmount = holyVisor.bonusTotalTokens();
}
// we don't want to divide by zero or underflow
// if totalBonusAmount is 0 -- then no bonuses are available for anyone
// if any of user metrics are 0 -- then for this user no bonues are available
if (totalBonusAmount == 0 || userMultiplier == 0 || userAmountCap == 0 || totalUnlocked == 0) {
return 0;
}
// we don't interfere with cap in UnlockUpdate(), but limit amount here for additional protection
if (totalUnlocked > totalBonusAmount) {
totalUnlocked = totalBonusAmount;
}
uint256 userClaimedBonus = claimedBonusTokens[_account];
uint256 userMigratedTokens = migratedTokens[_account];
uint256 userMigratedBonusCapped = userMigratedTokens.add(_currentlyMigratingAmount);
if (userMigratedBonusCapped > userAmountCap) {
userMigratedBonusCapped = userAmountCap; // even if bought more tokens than farmed, bonus would not go higher
}
// user multiplier should be in form of 1000000000000000000 meaning 1.0x 3750000000000000000 meaning 3.75x
userMigratedBonusCapped = userMultiplier.sub(1e18).mul(userMigratedBonusCapped).div(1e18);
uint256 unvestedBonusPortion = totalUnlocked.mul(1e18).div(totalBonusAmount); // fraction multiplied by 1e18
if (unvestedBonusPortion > 1e18) {
unvestedBonusPortion = 1e18;
}
// this should not be more than 1.0 (1 * 1e18)
//uint256 unvestedUserAmount = userMigratedBonusCapped.mul(unvestedBonusPortion).div(1e18); // this is total portion unlocked for user (incl. already claimed)
return userMigratedBonusCapped.mul(unvestedBonusPortion).div(1e18).sub(userClaimedBonus);
}
function getClaimableBonus() public view returns(uint256) {
return getClaimableBonusIncludingMigration(msg.sender, 0);
}
// get claimable bonus amount including migration
function getClaimableMigrationBonus() public view returns(uint256) {
uint256 userBalance = oldToken.balanceOf(msg.sender);
return getClaimableBonusIncludingMigration(msg.sender, userBalance);
}
// claim a bonus tokens for sender
function claimBonus() public {
require(bonusClaimEnabled, "bonus claim disabled");
claimBonusForAddress(msg.sender);
}
// NOTE: user can decrease allowance, thus, claim is not the same as migrate,
// during claim only actually migrated tokens are taken into consideration
// NOTE: require(bonusClaimEnabled, "bonus claim disabled"); is not placed here to save gas
// as this method is not to be called from the app, but for airdrop
// (getClaimableBonusIncludingMigration would return 0 anyway, but not revert)
// calculate and mint/claim bonus for a single address
function claimBonusForAddress(address _address) public {
uint256 bonusAmount = getClaimableBonusIncludingMigration(_address, 0);
//don't fail if amount is 0 here, it's used for batch airdrops too
if (bonusAmount > 0) {
newToken.mint(_address, bonusAmount); // mint new token to user address
emit ClaimedBonus(_address, bonusAmount);
claimedBonusTokens[_address] += bonusAmount;
}
}
// gets amounts of bonuses available for number of addresses
// and in case of non-zero amounts mints bonus tokens to user addresses
// function is public, but it can be gas-expensive and estimated to be called weekly in batches
function airdropBonuses(address[] memory /* calldata? */ addresses) public {
uint256 length = addresses.length;
for (uint256 i = 0; i < length; ++i) {
claimBonusForAddress(addresses[i]);
}
}
function setHolyVisor(address _visorAddress) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin oops only");
holyVisor = IHolyVisor(_visorAddress);
}
// set the total amount of bonus tokens (used in unlocked portion calculation)
function setMigrationWindow(uint256 _fromTimestamp, uint256 _toTimestamp) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
migrationStartTimestamp = _fromTimestamp;
migrationEndTimestamp = _toTimestamp;
}
function setMigrationEnabled(bool _enableMigration) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
migrationEnabled = _enableMigration;
}
function setBonusClaimEnabled(bool _enableBonusClaim) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
bonusClaimEnabled = _enableBonusClaim;
}
// all contracts that do not hold funds have this emergency function if someone occasionally
// transfers ERC20 tokens directly to this contract
// callable only by owner
function emergencyTransfer(address _token, address _destination, uint256 _amount) public {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Admin only");
IERC20(_token).safeTransfer(_destination, _amount);
}
}
/*
Some implementation details
---------------------------
Multiplier handling:
- contract has a map (user address -> multiplier value);
- this map is maintained with the following procedure:
- before bonus tokens are available, multipliers are populated using batch calls for all holders that have multiplier >1.0
after LP program finishes;
- off-chain backend provides the data for available multiplier to application;
Example:
- user has migrated 1500 tokens from HOLY to HH;
- user has achieved bonus of 3.175x for the amount of 5000 tokens;
This means, that maximum available bonus tokens are:
(3.175x - 1.0x) * 5000 = 2.175 * 5000 = 10875 tokens
Before user migrates more HOLY to HH, the maximum amount is capped at:
(1500/5000) * 10875 = 3262.5 tokens;
As there is additional vesting mechanics, the amount that is available for claiming currently is:
user_eligible_amount = (3262.5 - already_claimed_bonus)
unlocked_token_total = amount of HH tokens that are available currently (incrementing up to total_bonus_tokens)
user_bonus_share = (user_maximum_bonus_tokens / total_bonus_tokens)
if user_bonus_share * unlocked_token_total < user_eligible_amount
claimable = user_bonus_share * unlocked_token_total
else
claimable = user_eligible_amount (e.g. all bonus tokens are unvested or user migrated portion is smaller)
NOTE: by using such formula, user that e.g. sold many HOLY and migrated only a fraction to HH, gets available bonus
unlocked earlier (which may not be considered fair); So the unvesting should be implemented as
a fraction, not the absolute token amount, as:
unvested_bonus_portion = unlocked_token_total / total_bonus_tokens (changes from 0.0 to 1.0)
claimable = user_eligible_amount * unvested_bonus_portion
All data is available on-chain:
- how many tokens address had migrated is managed by this contract;
- how many bonus tokens address had received is managed by this contract;
- multipliers for addresses and cap amounts for addresses are written after LP migration ends into map in HolyVisor contract;
- total bonus token amount is written in HolyVisor contract;
- unlocked token amount is tracked by the HolyVisor contract;
*/ | gets amounts of bonuses available for number of addresses and in case of non-zero amounts mints bonus tokens to user addresses function is public, but it can be gas-expensive and estimated to be called weekly in batches | function airdropBonuses(address[] memory /* calldata? */ addresses) public {
uint256 length = addresses.length;
for (uint256 i = 0; i < length; ++i) {
claimBonusForAddress(addresses[i]);
}
}
| 1,416,943 | [
1,
14665,
30980,
434,
324,
265,
6117,
2319,
364,
1300,
434,
6138,
471,
316,
648,
434,
1661,
17,
7124,
30980,
312,
28142,
324,
22889,
2430,
358,
729,
6138,
445,
353,
1071,
16,
1496,
518,
848,
506,
16189,
17,
2749,
14315,
471,
13137,
358,
506,
2566,
4860,
715,
316,
13166,
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,
279,
6909,
1764,
38,
265,
6117,
12,
2867,
8526,
3778,
1748,
745,
892,
35,
1195,
6138,
13,
1071,
288,
203,
202,
11890,
5034,
769,
273,
6138,
18,
2469,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
769,
31,
965,
77,
13,
288,
203,
202,
202,
14784,
38,
22889,
1290,
1887,
12,
13277,
63,
77,
19226,
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
] |
./partial_match/1/0x9Cc188A25c96dbD7875c721D2B208Aa0B89f1fC4/sources/Airdropper.sol | require(_recipients.length > 0);IERC20 erc20Token = IERC20(_tokenAddress);pzssub = MasterChef(_masterChef);uint256 value = masterChef.pendingPizza(0,_recipients[j]); erc20Token.safeTransfer(_recipients[j], value.mul(value).mul(18).mul(1e6).div(1e18)); | function airTransfer( uint256 len) onlyOwner public returns (bool) {
for(uint j = 1; j < len+1; j++){
address userAddress = pzssub.addressIndexs(j);
token.safeTransfer(userAddress, 6*1e18);
}
return true;
}
| 4,293,137 | [
1,
6528,
24899,
27925,
18,
2469,
405,
374,
1769,
45,
654,
39,
3462,
225,
6445,
71,
3462,
1345,
273,
467,
654,
39,
3462,
24899,
2316,
1887,
1769,
84,
94,
1049,
373,
273,
13453,
39,
580,
74,
24899,
7525,
39,
580,
74,
1769,
11890,
5034,
460,
273,
225,
4171,
39,
580,
74,
18,
9561,
52,
452,
11939,
12,
20,
16,
67,
27925,
63,
78,
19226,
6445,
71,
3462,
1345,
18,
4626,
5912,
24899,
27925,
63,
78,
6487,
460,
18,
16411,
12,
1132,
2934,
16411,
12,
2643,
2934,
16411,
12,
21,
73,
26,
2934,
2892,
12,
21,
73,
2643,
10019,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
23350,
5912,
12,
2254,
5034,
562,
13,
1338,
5541,
1071,
1135,
261,
6430,
13,
288,
203,
27699,
3639,
364,
12,
11890,
525,
273,
404,
31,
525,
411,
562,
15,
21,
31,
525,
27245,
95,
203,
1850,
1758,
225,
729,
1887,
273,
225,
293,
94,
1049,
373,
18,
2867,
1016,
87,
12,
78,
1769,
203,
6647,
1147,
18,
4626,
5912,
12,
1355,
1887,
16,
1666,
14,
21,
73,
2643,
1769,
203,
3639,
289,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./SnapshotDelegatorPCVDeposit.sol";
import "./utils/VoteEscrowTokenManager.sol";
import "./utils/LiquidityGaugeManager.sol";
import "./utils/OZGovernorVoter.sol";
/// @title ANGLE Token PCV Deposit
/// @author Fei Protocol
contract AngleDelegatorPCVDeposit is SnapshotDelegatorPCVDeposit, VoteEscrowTokenManager, LiquidityGaugeManager, OZGovernorVoter {
address private constant ANGLE_TOKEN = 0x31429d1856aD1377A8A0079410B297e1a9e214c2;
address private constant ANGLE_VE_TOKEN = 0x0C462Dbb9EC8cD1630f1728B2CFD2769d09f0dd5;
address private constant ANGLE_GAUGE_MANAGER = 0x9aD7e7b0877582E14c17702EecF49018DD6f2367;
bytes32 private constant ANGLE_SNAPSHOT_SPACE = keccak256("anglegovernance.eth");
/// @notice ANGLE token manager
/// @param _core Fei Core for reference
/// @param _initialDelegate initial delegate for snapshot votes
constructor(
address _core,
address _initialDelegate
) SnapshotDelegatorPCVDeposit(
_core,
IERC20(ANGLE_TOKEN), // token used in reporting
ANGLE_SNAPSHOT_SPACE, // snapshot spaceId
_initialDelegate
) VoteEscrowTokenManager(
IERC20(ANGLE_TOKEN), // liquid token
IVeToken(ANGLE_VE_TOKEN), // vote-escrowed token
4 * 365 * 86400 // vote-escrow time = 4 years
) LiquidityGaugeManager(ANGLE_GAUGE_MANAGER) OZGovernorVoter() {}
/// @notice returns total balance of PCV in the Deposit
function balance() public view override returns (uint256) {
return _totalTokensManaged(); // liquid and vote-escrowed tokens
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../core/TribeRoles.sol";
import "../pcv/PCVDeposit.sol";
interface DelegateRegistry {
function setDelegate(bytes32 id, address delegate) external;
function clearDelegate(bytes32 id) external;
function delegation(address delegator, bytes32 id) external view returns(address delegatee);
}
/// @title Snapshot Delegator PCV Deposit
/// @author Fei Protocol
contract SnapshotDelegatorPCVDeposit is PCVDeposit {
event DelegateUpdate(address indexed oldDelegate, address indexed newDelegate);
/// @notice the Gnosis delegate registry used by snapshot
DelegateRegistry public constant DELEGATE_REGISTRY = DelegateRegistry(0x469788fE6E9E9681C6ebF3bF78e7Fd26Fc015446);
/// @notice the token that is being used for snapshot
IERC20 public immutable token;
/// @notice the keccak encoded spaceId of the snapshot space
bytes32 public spaceId;
/// @notice the snapshot delegate for the deposit
address public delegate;
/// @notice Snapshot Delegator PCV Deposit constructor
/// @param _core Fei Core for reference
/// @param _token snapshot token
/// @param _spaceId the id (or ENS name) of the snapshot space
constructor(
address _core,
IERC20 _token,
bytes32 _spaceId,
address _initialDelegate
) CoreRef(_core) {
token = _token;
spaceId = _spaceId;
_delegate(_initialDelegate);
}
/// @notice withdraw tokens from the PCV allocation
/// @param amountUnderlying of tokens withdrawn
/// @param to the address to send PCV to
function withdraw(address to, uint256 amountUnderlying)
external
override
onlyPCVController
{
_withdrawERC20(address(token), to, amountUnderlying);
}
/// @notice no-op
function deposit() external override {}
/// @notice returns total balance of PCV in the Deposit
function balance() public view virtual override returns (uint256) {
return token.balanceOf(address(this));
}
/// @notice display the related token of the balance reported
function balanceReportedIn() public view override returns (address) {
return address(token);
}
/// @notice sets the snapshot space ID
function setSpaceId(bytes32 _spaceId) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) {
spaceId = _spaceId;
}
/// @notice sets the snapshot delegate
function setDelegate(address newDelegate) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) {
_delegate(newDelegate);
}
/// @notice clears the delegate from snapshot
function clearDelegate() external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) {
address oldDelegate = delegate;
DELEGATE_REGISTRY.clearDelegate(spaceId);
emit DelegateUpdate(oldDelegate, address(0));
}
function _delegate(address newDelegate) internal {
address oldDelegate = delegate;
DELEGATE_REGISTRY.setDelegate(spaceId, newDelegate);
delegate = newDelegate;
emit DelegateUpdate(oldDelegate, newDelegate);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/**
@title Tribe DAO ACL Roles
@notice Holds a complete list of all roles which can be held by contracts inside Tribe DAO.
Roles are broken up into 3 categories:
* Major Roles - the most powerful roles in the Tribe DAO which should be carefully managed.
* Admin Roles - roles with management capability over critical functionality. Should only be held by automated or optimistic mechanisms
* Minor Roles - operational roles. May be held or managed by shorter optimistic timelocks or trusted multisigs.
*/
library TribeRoles {
/*///////////////////////////////////////////////////////////////
Major Roles
//////////////////////////////////////////////////////////////*/
/// @notice the ultimate role of Tribe. Controls all other roles and protocol functionality.
bytes32 internal constant GOVERNOR = keccak256("GOVERN_ROLE");
/// @notice the protector role of Tribe. Admin of pause, veto, revoke, and minor roles
bytes32 internal constant GUARDIAN = keccak256("GUARDIAN_ROLE");
/// @notice the role which can arbitrarily move PCV in any size from any contract
bytes32 internal constant PCV_CONTROLLER = keccak256("PCV_CONTROLLER_ROLE");
/// @notice can mint FEI arbitrarily
bytes32 internal constant MINTER = keccak256("MINTER_ROLE");
/*///////////////////////////////////////////////////////////////
Admin Roles
//////////////////////////////////////////////////////////////*/
/// @notice can manage the majority of Tribe protocol parameters. Sets boundaries for MINOR_PARAM_ROLE.
bytes32 internal constant PARAMETER_ADMIN = keccak256("PARAMETER_ADMIN");
/// @notice manages the Collateralization Oracle as well as other protocol oracles.
bytes32 internal constant ORACLE_ADMIN = keccak256("ORACLE_ADMIN_ROLE");
/// @notice manages TribalChief incentives and related functionality.
bytes32 internal constant TRIBAL_CHIEF_ADMIN = keccak256("TRIBAL_CHIEF_ADMIN_ROLE");
/// @notice admin of PCVGuardian
bytes32 internal constant PCV_GUARDIAN_ADMIN = keccak256("PCV_GUARDIAN_ADMIN_ROLE");
/// @notice admin of all Minor Roles
bytes32 internal constant MINOR_ROLE_ADMIN = keccak256("MINOR_ROLE_ADMIN");
/// @notice admin of the Fuse protocol
bytes32 internal constant FUSE_ADMIN = keccak256("FUSE_ADMIN");
/// @notice capable of vetoing DAO votes or optimistic timelocks
bytes32 internal constant VETO_ADMIN = keccak256("VETO_ADMIN");
/// @notice capable of setting FEI Minters within global rate limits and caps
bytes32 internal constant MINTER_ADMIN = keccak256("MINTER_ADMIN");
/// @notice manages the constituents of Optimistic Timelocks, including Proposers and Executors
bytes32 internal constant OPTIMISTIC_ADMIN = keccak256("OPTIMISTIC_ADMIN");
/// @notice manages meta-governance actions, like voting & delegating.
/// Also used to vote for gauge weights & similar liquid governance things.
bytes32 internal constant METAGOVERNANCE_VOTE_ADMIN = keccak256("METAGOVERNANCE_VOTE_ADMIN");
/// @notice allows to manage locking of vote-escrowed tokens, and staking/unstaking
/// governance tokens from a pre-defined contract in order to eventually allow voting.
/// Examples: ANGLE <> veANGLE, AAVE <> stkAAVE, CVX <> vlCVX, CRV > cvxCRV.
bytes32 internal constant METAGOVERNANCE_TOKEN_STAKING = keccak256("METAGOVERNANCE_TOKEN_STAKING");
/// @notice manages whitelisting of gauges where the protocol's tokens can be staked
bytes32 internal constant METAGOVERNANCE_GAUGE_ADMIN = keccak256("METAGOVERNANCE_GAUGE_ADMIN");
/// @notice manages staking to & unstaking from gauges of the protocol's tokens
bytes32 internal constant METAGOVERNANCE_GAUGE_STAKING = keccak256("METAGOVERNANCE_GAUGE_STAKING");
/*///////////////////////////////////////////////////////////////
Minor Roles
//////////////////////////////////////////////////////////////*/
/// @notice capable of poking existing LBP auctions to exchange tokens.
bytes32 internal constant LBP_SWAP_ROLE = keccak256("SWAP_ADMIN_ROLE");
/// @notice capable of engaging with Votium for voting incentives.
bytes32 internal constant VOTIUM_ROLE = keccak256("VOTIUM_ADMIN_ROLE");
/// @notice capable of changing parameters within non-critical ranges
bytes32 internal constant MINOR_PARAM_ROLE = keccak256("MINOR_PARAM_ROLE");
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../refs/CoreRef.sol";
import "./IPCVDeposit.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
/// @title abstract contract for withdrawing ERC-20 tokens using a PCV Controller
/// @author Fei Protocol
abstract contract PCVDeposit is IPCVDeposit, CoreRef {
using SafeERC20 for IERC20;
/// @notice withdraw ERC20 from the contract
/// @param token address of the ERC20 to send
/// @param to address destination of the ERC20
/// @param amount quantity of ERC20 to send
function withdrawERC20(
address token,
address to,
uint256 amount
) public virtual override onlyPCVController {
_withdrawERC20(token, to, amount);
}
function _withdrawERC20(
address token,
address to,
uint256 amount
) internal {
IERC20(token).safeTransfer(to, amount);
emit WithdrawERC20(msg.sender, token, to, amount);
}
/// @notice withdraw ETH from the contract
/// @param to address to send ETH
/// @param amountOut amount of ETH to send
function withdrawETH(address payable to, uint256 amountOut) external virtual override onlyPCVController {
Address.sendValue(to, amountOut);
emit WithdrawETH(msg.sender, to, amountOut);
}
function balance() public view virtual override returns(uint256);
function resistantBalanceAndFei() public view virtual override returns(uint256, uint256) {
return (balance(), 0);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
/// @title A Reference to Core
/// @author Fei Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private immutable _core;
IFei private immutable _fei;
IERC20 private immutable _tribe;
/// @notice a role used with a subset of governor permissions for this contract only
bytes32 public override CONTRACT_ADMIN_ROLE;
constructor(address coreAddress) {
_core = ICore(coreAddress);
_fei = ICore(coreAddress).fei();
_tribe = ICore(coreAddress).tribe();
_setContractAdminRole(ICore(coreAddress).GOVERN_ROLE());
}
function _initialize(address) internal {} // no-op for backward compatibility
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernorOrAdmin() {
require(
_core.isGovernor(msg.sender) ||
isContractAdmin(msg.sender),
"CoreRef: Caller is not a governor or contract admin"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier isGovernorOrGuardianOrAdmin() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender) ||
isContractAdmin(msg.sender),
"CoreRef: Caller is not governor or guardian or admin");
_;
}
// Named onlyTribeRole to prevent collision with OZ onlyRole modifier
modifier onlyTribeRole(bytes32 role) {
require(_core.hasRole(role, msg.sender), "UNAUTHORIZED");
_;
}
// Modifiers to allow any combination of roles
modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) {
require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED");
_;
}
modifier hasAnyOfThreeRoles(bytes32 role1, bytes32 role2, bytes32 role3) {
require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender), "UNAUTHORIZED");
_;
}
modifier hasAnyOfFourRoles(bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4) {
require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender), "UNAUTHORIZED");
_;
}
modifier hasAnyOfFiveRoles(bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5) {
require(_core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender), "UNAUTHORIZED");
_;
}
modifier onlyFei() {
require(msg.sender == address(_fei), "CoreRef: Caller is not FEI");
_;
}
/// @notice sets a new admin role for this contract
function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor {
_setContractAdminRole(newContractAdminRole);
}
/// @notice returns whether a given address has the admin role for this contract
function isContractAdmin(address _admin) public view override returns (bool) {
return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Fei contract referenced by Core
/// @return IFei implementation address
function fei() public view override returns (IFei) {
return _fei;
}
/// @notice address of the Tribe contract referenced by Core
/// @return IERC20 implementation address
function tribe() public view override returns (IERC20) {
return _tribe;
}
/// @notice fei balance of contract
/// @return fei amount held
function feiBalance() public view override returns (uint256) {
return _fei.balanceOf(address(this));
}
/// @notice tribe balance of contract
/// @return tribe amount held
function tribeBalance() public view override returns (uint256) {
return _tribe.balanceOf(address(this));
}
function _burnFeiHeld() internal {
_fei.burn(feiBalance());
}
function _mintFei(address to, uint256 amount) internal virtual {
if (amount != 0) {
_fei.mint(to, amount);
}
}
function _setContractAdminRole(bytes32 newContractAdminRole) internal {
bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE;
CONTRACT_ADMIN_ROLE = newContractAdminRole;
emit ContractAdminRoleUpdate(oldContractAdminRole, newContractAdminRole);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Fei Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed oldCore, address indexed newCore);
event ContractAdminRoleUpdate(bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole);
// ----------- Governor only state changing api -----------
function setContractAdminRole(bytes32 newContractAdminRole) external;
// ----------- Governor or Guardian only state changing api -----------
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function fei() external view returns (IFei);
function tribe() external view returns (IERC20);
function feiBalance() external view returns (uint256);
function tribeBalance() external view returns (uint256);
function CONTRACT_ADMIN_ROLE() external view returns (bytes32);
function isContractAdmin(address admin) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IPermissions.sol";
import "../fei/IFei.sol";
/// @title Core Interface
/// @author Fei Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event FeiUpdate(address indexed _fei);
event TribeUpdate(address indexed _tribe);
event GenesisGroupUpdate(address indexed _genesisGroup);
event TribeAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setFei(address token) external;
function setTribe(address token) external;
function allocateTribe(address to, uint256 amount) external;
// ----------- Getters -----------
function fei() external view returns (IFei);
function tribe() external view returns (IERC20);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "./IPermissionsRead.sol";
/// @title Permissions interface
/// @author Fei Protocol
interface IPermissions is IAccessControl, IPermissionsRead {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function GUARDIAN_ROLE() external view returns (bytes32);
function GOVERN_ROLE() external view returns (bytes32);
function BURNER_ROLE() external view returns (bytes32);
function MINTER_ROLE() external view returns (bytes32);
function PCV_CONTROLLER_ROLE() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title Permissions Read interface
/// @author Fei Protocol
interface IPermissionsRead {
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title FEI stablecoin interface
/// @author Fei Protocol
interface IFei is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentivized,
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address account, address incentive) external;
// ----------- Getters -----------
function incentiveContract(address account) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
import "./IPCVDepositBalances.sol";
/// @title a PCV Deposit interface
/// @author Fei Protocol
interface IPCVDeposit is IPCVDepositBalances {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
event WithdrawERC20(
address indexed _caller,
address indexed _token,
address indexed _to,
uint256 _amount
);
event WithdrawETH(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external;
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function withdrawERC20(address token, address to, uint256 amount) external;
function withdrawETH(address payable to, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.4;
/// @title a PCV Deposit interface for only balance getters
/// @author Fei Protocol
interface IPCVDepositBalances {
// ----------- Getters -----------
/// @notice gets the effective balance of "balanceReportedIn" token if the deposit were fully withdrawn
function balance() external view returns (uint256);
/// @notice gets the token address in which this deposit returns its balance
function balanceReportedIn() external view returns (address);
/// @notice gets the resistant token balance and protocol owned fei of this deposit
function resistantBalanceAndFei() external view returns (uint256, uint256);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../refs/CoreRef.sol";
import "../../core/TribeRoles.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IVeToken {
function balanceOf(address) external view returns (uint256);
function locked(address) external view returns (uint256);
function create_lock(uint256 value, uint256 unlock_time) external;
function increase_amount(uint256 value) external;
function increase_unlock_time(uint256 unlock_time) external;
function withdraw() external;
function locked__end(address) external view returns (uint256);
function checkpoint() external;
}
/// @title Vote-escrowed Token Manager
/// Used to permanently lock tokens in a vote-escrow contract, and refresh
/// the lock duration as needed.
/// @author Fei Protocol
abstract contract VoteEscrowTokenManager is CoreRef {
// Events
event Lock(uint256 cummulativeTokensLocked, uint256 lockHorizon);
event Unlock(uint256 tokensUnlocked);
/// @notice One week, in seconds. Vote-locking is rounded down to weeks.
uint256 private constant WEEK = 7 * 86400; // 1 week, in seconds
/// @notice The lock duration of veTokens
uint256 public lockDuration;
/// @notice The vote-escrowed token address
IVeToken public immutable veToken;
/// @notice The token address
IERC20 public immutable liquidToken;
/// @notice VoteEscrowTokenManager token Snapshot Delegator PCV Deposit constructor
/// @param _liquidToken the token to lock for vote-escrow
/// @param _veToken the vote-escrowed token used in governance
/// @param _lockDuration amount of time (in seconds) tokens will be vote-escrowed for
constructor(
IERC20 _liquidToken,
IVeToken _veToken,
uint256 _lockDuration
) {
liquidToken = _liquidToken;
veToken = _veToken;
lockDuration = _lockDuration;
}
/// @notice Set the amount of time tokens will be vote-escrowed for in lock() calls
function setLockDuration(uint256 newLockDuration) external onlyTribeRole(TribeRoles.METAGOVERNANCE_TOKEN_STAKING) {
lockDuration = newLockDuration;
}
/// @notice Deposit tokens to get veTokens. Set lock duration to lockDuration.
/// The only way to withdraw tokens will be to pause this contract
/// for lockDuration and then call exitLock().
function lock() external whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_TOKEN_STAKING) {
uint256 tokenBalance = liquidToken.balanceOf(address(this));
uint256 locked = veToken.locked(address(this));
uint256 lockHorizon = ((block.timestamp + lockDuration) / WEEK) * WEEK;
// First lock
if (tokenBalance != 0 && locked == 0) {
liquidToken.approve(address(veToken), tokenBalance);
veToken.create_lock(tokenBalance, lockHorizon);
}
// Increase amount of tokens locked & refresh duration to lockDuration
else if (tokenBalance != 0 && locked != 0) {
liquidToken.approve(address(veToken), tokenBalance);
veToken.increase_amount(tokenBalance);
if (veToken.locked__end(address(this)) != lockHorizon) {
veToken.increase_unlock_time(lockHorizon);
}
}
// No additional tokens to lock, just refresh duration to lockDuration
else if (tokenBalance == 0 && locked != 0) {
veToken.increase_unlock_time(lockHorizon);
}
// If tokenBalance == 0 and locked == 0, there is nothing to do.
emit Lock(tokenBalance + locked, lockHorizon);
}
/// @notice Exit the veToken lock. For this function to be called and not
/// revert, tokens had to be locked previously, and the contract must have
/// been paused for lockDuration in order to prevent lock extensions
/// by calling lock(). This function will recover tokens on the contract,
/// which can then be moved by calling withdraw() as a PCVController if the
/// contract is also a PCVDeposit, for instance.
function exitLock() external onlyTribeRole(TribeRoles.METAGOVERNANCE_TOKEN_STAKING) {
veToken.withdraw();
emit Unlock(liquidToken.balanceOf(address(this)));
}
/// @notice returns total balance of tokens, vote-escrowed or liquid.
function _totalTokensManaged() internal view returns (uint256) {
return liquidToken.balanceOf(address(this)) + veToken.locked(address(this));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../refs/CoreRef.sol";
import "../../core/TribeRoles.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface ILiquidityGauge {
function deposit(uint256 value) external;
function withdraw(uint256 value, bool claim_rewards) external;
function claim_rewards() external;
function balanceOf(address) external view returns(uint256);
function staking_token() external view returns(address);
function reward_tokens(uint256 i) external view returns (address token);
function reward_count() external view returns (uint256 nTokens);
}
interface ILiquidityGaugeController {
function vote_for_gauge_weights(address gauge_addr, uint256 user_weight) external;
function last_user_vote(address user, address gauge) external view returns(uint256);
function vote_user_power(address user) external view returns(uint256);
function gauge_types(address gauge) external view returns(int128);
}
/// @title Liquidity gauge manager, used to stake tokens in liquidity gauges.
/// @author Fei Protocol
abstract contract LiquidityGaugeManager is CoreRef {
// Events
event GaugeControllerChanged(address indexed oldController, address indexed newController);
event GaugeSetForToken(address indexed token, address indexed gauge);
event GaugeVote(address indexed gauge, uint256 amount);
event GaugeStake(address indexed gauge, uint256 amount);
event GaugeUnstake(address indexed gauge, uint256 amount);
event GaugeRewardsClaimed(address indexed gauge, address indexed token, uint256 amount);
/// @notice address of the gauge controller used for voting
address public gaugeController;
/// @notice mapping of token staked to gauge address
mapping(address=>address) public tokenToGauge;
constructor(address _gaugeController) {
gaugeController = _gaugeController;
}
/// @notice Set the gauge controller used for gauge weight voting
/// @param _gaugeController the gauge controller address
function setGaugeController(address _gaugeController) public onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) {
require(gaugeController != _gaugeController, "LiquidityGaugeManager: same controller");
address oldController = gaugeController;
gaugeController = _gaugeController;
emit GaugeControllerChanged(oldController, gaugeController);
}
/// @notice Set gauge for a given token.
/// @param token the token address to stake in gauge
/// @param gaugeAddress the address of the gauge where to stake token
function setTokenToGauge(
address token,
address gaugeAddress
) public onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) {
require(ILiquidityGauge(gaugeAddress).staking_token() == token, "LiquidityGaugeManager: wrong gauge for token");
require(ILiquidityGaugeController(gaugeController).gauge_types(gaugeAddress) >= 0, "LiquidityGaugeManager: wrong gauge address");
tokenToGauge[token] = gaugeAddress;
emit GaugeSetForToken(token, gaugeAddress);
}
/// @notice Vote for a gauge's weight
/// @param token the address of the token to vote for
/// @param gaugeWeight the weight of gaugeAddress in basis points [0, 10_000]
function voteForGaugeWeight(
address token,
uint256 gaugeWeight
) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) {
address gaugeAddress = tokenToGauge[token];
require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured");
ILiquidityGaugeController(gaugeController).vote_for_gauge_weights(gaugeAddress, gaugeWeight);
emit GaugeVote(gaugeAddress, gaugeWeight);
}
/// @notice Stake tokens in a gauge
/// @param token the address of the token to stake in the gauge
/// @param amount the amount of tokens to stake in the gauge
function stakeInGauge(
address token,
uint256 amount
) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) {
address gaugeAddress = tokenToGauge[token];
require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured");
IERC20(token).approve(gaugeAddress, amount);
ILiquidityGauge(gaugeAddress).deposit(amount);
emit GaugeStake(gaugeAddress, amount);
}
/// @notice Stake all tokens held in a gauge
/// @param token the address of the token to stake in the gauge
function stakeAllInGauge(address token) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) {
address gaugeAddress = tokenToGauge[token];
require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured");
uint256 amount = IERC20(token).balanceOf(address(this));
IERC20(token).approve(gaugeAddress, amount);
ILiquidityGauge(gaugeAddress).deposit(amount);
emit GaugeStake(gaugeAddress, amount);
}
/// @notice Unstake tokens from a gauge
/// @param token the address of the token to unstake from the gauge
/// @param amount the amount of tokens to unstake from the gauge
function unstakeFromGauge(
address token,
uint256 amount
) public whenNotPaused onlyTribeRole(TribeRoles.METAGOVERNANCE_GAUGE_ADMIN) {
address gaugeAddress = tokenToGauge[token];
require(gaugeAddress != address(0), "LiquidityGaugeManager: token has no gauge configured");
ILiquidityGauge(gaugeAddress).withdraw(amount, false);
emit GaugeUnstake(gaugeAddress, amount);
}
/// @notice Claim rewards associated to a gauge where this contract stakes
/// tokens.
function claimGaugeRewards(address gaugeAddress) public whenNotPaused {
uint256 nTokens = ILiquidityGauge(gaugeAddress).reward_count();
address[] memory tokens = new address[](nTokens);
uint256[] memory amounts = new uint256[](nTokens);
for (uint256 i = 0; i < nTokens; i++) {
tokens[i] = ILiquidityGauge(gaugeAddress).reward_tokens(i);
amounts[i] = IERC20(tokens[i]).balanceOf(address(this));
}
ILiquidityGauge(gaugeAddress).claim_rewards();
for (uint256 i = 0; i < nTokens; i++) {
amounts[i] = IERC20(tokens[i]).balanceOf(address(this)) - amounts[i];
emit GaugeRewardsClaimed(gaugeAddress, tokens[i], amounts[i]);
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../refs/CoreRef.sol";
import "../../core/TribeRoles.sol";
interface IOZGovernor {
function propose(
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) external returns (uint256 proposalId);
function castVote(uint256 proposalId, uint8 support) external returns (uint256 weight);
function state(uint256 proposalId) external view returns (uint256);
}
/// @title Abstract class to interact with an OZ governor.
/// @author Fei Protocol
abstract contract OZGovernorVoter is CoreRef {
// Events
event Proposed(IOZGovernor indexed governor, uint256 proposalId);
event Voted(IOZGovernor indexed governor, uint256 proposalId, uint256 weight, uint8 support);
/// @notice propose a new proposal on the target governor.
function propose(
IOZGovernor governor,
address[] memory targets,
uint256[] memory values,
bytes[] memory calldatas,
string memory description
) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) returns (uint256) {
uint256 proposalId = governor.propose(targets, values, calldatas, description);
emit Proposed(governor, proposalId);
return proposalId;
}
/// @notice cast a vote on a given proposal on the target governor.
function castVote(
IOZGovernor governor,
uint256 proposalId,
uint8 support
) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) returns (uint256) {
uint256 weight = governor.castVote(proposalId, support);
emit Voted(governor, proposalId, weight, support);
return weight;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/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() {
_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
// 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 (access/AccessControl.sol)
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 revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface 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
// 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);
} | @notice sets the snapshot delegate | function setDelegate(address newDelegate) external onlyTribeRole(TribeRoles.METAGOVERNANCE_VOTE_ADMIN) {
_delegate(newDelegate);
}
| 602,811 | [
1,
4424,
326,
4439,
7152,
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,
444,
9586,
12,
2867,
394,
9586,
13,
3903,
1338,
1070,
495,
73,
2996,
12,
1070,
495,
73,
6898,
18,
958,
7927,
12959,
50,
4722,
67,
16169,
1448,
67,
15468,
13,
288,
203,
3639,
389,
22216,
12,
2704,
9586,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "./Ownable.sol";
import "./SafeMath.sol";
/**
* @notice Stakeable is a contract who is ment to be inherited by other contract that wants Staking capabilities
*/
contract Stakeable is Ownable{
// we don't want to have any security issues
using SafeMath for uint256;
/**
* @notice Constructor since this contract is not ment to be used without inheritance
* push once to stakeholders for it to work proplerly
*/
constructor() {
// This push is needed so we avoid index 0 causing bug of index-1
stakeholders.push();
// populate rewards
_rewards.push(uint(200)); // 2.00% per month
_rewards.push(uint(300)); // 3.00% per month
_rewards.push(uint(500)); // 5.00% per month
_rewards.push(uint(700)); // 7.00% per month
_rewards.push(uint(900)); // 8.00%s per month
// populate periods with monts
_periods.push(uint(1));
_periods.push(uint(3));
_periods.push(uint(6));
_periods.push(uint(12));
}
/**
* @notice
* A stake struct is used to represent the way we store stakes,
* A Stake will contain the users address, the amount staked and a timestamp,
* Since which is when the stake was made
*/
struct Stake{
address user;
uint256 amount;
uint256 since;
uint8 period; // this represent the stake interval
// values 0 - 1 month, 1 - 3 months, 2 - 6 months, 3 - 12 months
// This claimable field is new and used to tell how big of a reward is currently available
uint256 claimable;
}
/**
* @notice Stakeholder is a staker that has active stakes
*/
struct Stakeholder{
address user;
Stake[] address_stakes;
}
/*
* StakingSummary is a struct that is used to contain all stakes performed by a certain account
*/
struct StakingSummary{
uint256 total_amount;
Stake[] stakes;
}
uint[] private _rewards;
uint[] private _periods;
/**
* @notice
* This is a array where we store all Stakes that are performed on the Contract
* The stakes for each address are stored at a certain index, the index can be found using the stakes mapping
*/
Stakeholder[] internal stakeholders;
/**
* @notice
* stakes is used to keep track of the INDEX for the stakers in the stakes array
*/
mapping(address => uint256) internal stakes;
/**
* @notice Staked event is triggered whenever a user stakes tokens, address is indexed to make it filterable
*/
event Staked(address indexed user, uint256 amount, uint256 index, uint256 timestamp);
/**
* @notice getReward will get the reward value for a specific period
*/
function getReward(uint8 index) public view returns (uint) {
return _rewards[index];
}
/**
* @notice setReward will set a specific value for index
*/
function setReward(uint8 index, uint value) external onlyOwner{
_rewards[index] = value;
}
/**
* @notice getRewards will get the reward value for a specific period
*/
function getRewards() public view returns (uint[] memory) {
return _rewards;
}
/**
* @notice getPeriod will get the period in months for a specific index
*/
function getPeriod(uint8 index) public view returns (uint) {
return _periods[index];
}
/**
* @notice setPeriod will get the period in months for a specific index
*/
function setPeriod(uint8 index, uint value) external onlyOwner{
_periods[index] = value;
}
/**
* @notice getPeriods willreturn all periods
*/
function getPeriods() public view returns (uint[] memory) {
return _periods;
}
/**
* @notice _addStakeholder takes care of adding a stakeholder to the stakeholders array
*/
function _addStakeholder(address staker) internal returns (uint256){
// Push a empty item to the Array to make space for our new stakeholder
stakeholders.push();
// Calculate the index of the last item in the array by Len-1
uint256 userIndex = stakeholders.length - 1;
// Assign the address to the new index
stakeholders[userIndex].user = staker;
// Add index to the stakeHolders
stakes[staker] = userIndex;
return userIndex;
}
/**
* @notice
* _Stake is used to make a stake for an sender. It will remove the amount staked from the stakers account and place those tokens inside a stake container
* StakeID
*/
function _stake(uint256 _amount, uint8 _period) internal{
// Simple check so that user does not stake 0
require(_amount > 0, "Cannot stake nothing");
// Mappings in solidity creates all values, but empty, so we can just check the address
uint256 index = stakes[msg.sender];
// block.timestamp = timestamp of the current block in seconds since the epoch
uint256 timestamp = block.timestamp;
// See if the staker already has a staked index or if its the first time
if(index == 0){
// This stakeholder stakes for the first time
// We need to add him to the stakeHolders and also map it into the Index of the stakes
// The index returned will be the index of the stakeholder in the stakeholders array
index = _addStakeholder(msg.sender);
}
// Use the index to push a new Stake
// push a newly created Stake with the current block timestamp.
stakeholders[index].address_stakes.push(Stake(msg.sender, _amount, timestamp, _period, 0));
// Emit an event that the stake has occured
emit Staked(msg.sender, _amount, index,timestamp);
}
/**
* @notice
* calculateStakeReward is used to calculate how much a user should be rewarded for their stakes
* for the duration of the stake
*/
function calculateStakeReward(Stake memory _current_stake) internal view returns(uint256){
// first we check if we have the right to withdraw the stake by period
uint8 periodIndex = _current_stake.period;
uint reward = getReward(periodIndex);
uint period = getPeriod(periodIndex);
require (period>0, "We cannot stake for a 0 period");
require (reward>0, "We cannot stake for 0 reward");
uint256 divStake = _current_stake.amount.div(100);
uint256 divReward = reward.div(100);
uint256 stakeReward = divStake.mul(divReward).mul(period);
require (stakeReward>0, "The reward is 0 (not ok)");
return stakeReward;
}
/**
* @notice
* withdrawStake takes in an amount and a index of the stake and will remove tokens from that stake
* Notice index of the stake is the users stake counter, starting at 0 for the first stake
* Will return the amount to MINT onto the acount
* Will also calculateStakeReward and reset timer
*/
function _withdrawStake(uint256 amount, uint256 index) internal returns(uint256){
// Grab user_index which is the index to use to grab the Stake[]
uint256 user_index = stakes[msg.sender];
Stake memory current_stake = stakeholders[user_index].address_stakes[index];
require(current_stake.amount >= amount, "Staking: Cannot withdraw more than you have staked");
// check to see if the stake is locked
uint stakeAge = (block.timestamp - current_stake.since)/(3600*24*30); // number of months
uint period = getPeriod(current_stake.period);
require (stakeAge >= period, "Stake is locked for the initial defined period");
// Calculate available Reward first before we start modifying data
uint256 reward = calculateStakeReward(current_stake);
// Remove by subtracting the money unstaked
current_stake.amount = current_stake.amount - amount;
// If stake is empty, 0, then remove it from the array of stakes
if (current_stake.amount == 0){
delete stakeholders[user_index].address_stakes[index];
} else {
// If not empty then replace the value of it
stakeholders[user_index].address_stakes[index].amount = current_stake.amount;
// Reset timer of stake
stakeholders[user_index].address_stakes[index].since = block.timestamp;
}
return amount+reward;
}
/**
* @notice
* hasStake is used to check if a account has stakes and the total amount along with all the seperate stakes
*/
function hasStake(address _staker) public view returns(StakingSummary memory){
// totalStakeAmount is used to count total staked amount of the address
uint256 totalStakeAmount;
// Keep a summary in memory since we need to calculate this
StakingSummary memory summary = StakingSummary(0, stakeholders[stakes[_staker]].address_stakes);
// Itterate all stakes and grab amount of stakes
for (uint256 s = 0; s < summary.stakes.length; s += 1){
uint256 availableReward = calculateStakeReward(summary.stakes[s]);
summary.stakes[s].claimable = availableReward;
totalStakeAmount = totalStakeAmount+summary.stakes[s].amount;
}
// Assign calculate amount to summary
summary.total_amount = totalStakeAmount;
return summary;
}
} | * @notice Stakeholder is a staker that has active stakes/ | struct Stakeholder{
address user;
Stake[] address_stakes;
}
| 14,084,098 | [
1,
510,
911,
4505,
353,
279,
384,
6388,
716,
711,
2695,
384,
3223,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
934,
911,
4505,
95,
203,
3639,
1758,
729,
31,
203,
3639,
934,
911,
8526,
1758,
67,
334,
3223,
31,
203,
540,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
Shibasaki - $SHIBASAKI
🌍 Website: http://shibasakieth.com/
💬 Telegram: https://t.me/ShibasakiERC20
🕊 Twitter: https://twitter.com/@shibasakierc20
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.9;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract Shibasaki is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
address public constant deadAddress = address(0xdead);
bool private swapping;
address public marketingWallet;
address public devWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
uint256 public percentForLPBurn = 25; // 25 = .25%
bool public lpBurnEnabled = true;
uint256 public lpBurnFrequency = 3600 seconds;
// uint256 public lastLpBurnTime;
uint256 public manualBurnFrequency = 30 minutes;
uint256 public lastManualLpBurnTime;
bool public limitsInEffect = false;
bool public tradingActive = true;
bool public swapEnabled = false;
bool public stakingPhaseEnabled = false;
// Anti-bot and anti-whale
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last transfers
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyDevFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellDevFee;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event devWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Shibasaki", "SHIBASAKI") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 3;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 3;
uint256 _sellMarketingFee = 75;
uint256 _sellLiquidityFee = 15;
uint256 _sellDevFee = 10;
uint256 totalSupply = 10 * 1e9 * 1e18;
maxTransactionAmount = totalSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn
maxWallet = totalSupply * 10 / 1000; // 1% maxWallet
swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
marketingWallet = address(owner()); // set as marketing wallet
devWallet = address(owner()); // set as dev wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
// once enabled, can never be turned off
function launch() external onlyOwner {
tradingActive = true;
swapEnabled = true;
// lastLpBurnTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool){
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool){
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**18);
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**18);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyDevFee = _devFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
require(buyTotalFees <= 20, "Must keep fees at 20% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _devFee) external onlyOwner {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellDevFee = _devFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
require(sellTotalFees <= 100, "Must keep fees at 100% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateMarketingWallet(address newMarketingWallet) external onlyOwner {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateDevWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function updateStakingWallet(address newWallet) external onlyOwner {
emit devWalletUpdated(newWallet, devWallet);
devWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
event BoughtEarly(address indexed sniper);
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if(
canSwap &&
swapEnabled &&
!swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
swapping = true;
swapBack();
swapping = false;
}
// if(!swapping && automatedMarketMakerPairs[to] && lpBurnEnabled && block.timestamp >= lastLpBurnTime + lpBurnFrequency && !_isExcludedFromFees[from]){
// autoBurnLiquidityPairTokens();
// }
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForDev += fees * sellDevFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForDev += fees * buyDevFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees > 0){
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
deadAddress,
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev;
bool success;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > swapTokensAtAmount * 20){
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDev = 0;
(success,) = address(devWallet).call{value: ethForDev}("");
if(liquidityTokens > 0 && ethForLiquidity > 0){
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity);
}
(success,) = address(marketingWallet).call{value: address(this).balance}("");
}
function setAutoLPBurnSettings(uint256 _frequencyInSeconds, uint256 _percent, bool _Enabled) external onlyOwner {
require(_frequencyInSeconds >= 600, "cannot set buyback more often than every 10 minutes");
require(_percent <= 1000 && _percent >= 0, "Must set auto LP burn percent between 0% and 10%");
lpBurnFrequency = _frequencyInSeconds;
percentForLPBurn = _percent;
lpBurnEnabled = _Enabled;
}
function autoBurnLiquidityPairTokens() internal returns (bool){
// lastLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percentForLPBurn).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit AutoNukeLP();
return true;
}
function manualBurnLiquidityPairTokens(uint256 percent) external onlyOwner returns (bool){
require(block.timestamp > lastManualLpBurnTime + manualBurnFrequency , "Must wait for cooldown to finish");
require(percent <= 1000, "May not nuke more than 10% of tokens in LP");
lastManualLpBurnTime = block.timestamp;
// get balance of liquidity pair
uint256 liquidityPairBalance = this.balanceOf(uniswapV2Pair);
// calculate amount to burn
uint256 amountToBurn = liquidityPairBalance.mul(percent).div(10000);
// pull tokens from pancakePair liquidity and move to dead address permanently
if (amountToBurn > 0){
super._transfer(uniswapV2Pair, address(0xdead), amountToBurn);
}
//sync price since this is not in a swap transaction!
IUniswapV2Pair pair = IUniswapV2Pair(uniswapV2Pair);
pair.sync();
emit ManualNukeLP();
return true;
}
} | exclude from paying fees or having max transaction amount | constructor() ERC20("Shibasaki", "SHIBASAKI") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 3;
uint256 _buyLiquidityFee = 3;
uint256 _buyDevFee = 3;
uint256 _sellMarketingFee = 75;
uint256 _sellLiquidityFee = 15;
uint256 _sellDevFee = 10;
uint256 totalSupply = 10 * 1e9 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 5,971,026 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1435,
4232,
39,
3462,
2932,
1555,
495,
345,
581,
77,
3113,
315,
2664,
13450,
3033,
14607,
45,
7923,
288,
203,
540,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
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,
540,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
540,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
540,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
890,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
890,
31,
203,
3639,
2254,
5034,
389,
2
] |
./full_match/1/0xB51B89140D168734d656B2C8959A4E3F7205b8b4/sources/contracts/modules/KresusRelayer.sol | * @notice cancels a transaction which was queued. @param _vault The target vault. @param _data The data for the relayed transaction. @param _nonce The nonce used to prevent replay attacks. @param _signature The signature needed to validate cancel./ | function cancel(
address _vault,
bytes calldata _data,
uint256 _nonce,
bytes memory _signature
)
external
{
bytes32 _actionHash = getSignHash(_vault, 0, _data, _nonce);
bytes32 _cancelHash = getSignHash(_vault, 0, "0x", _nonce);
require(isActionQueued(_vault, _actionHash), "KR: Invalid hash");
Signature _sig = getCancelRequiredSignatures(_vault, _data);
require(
validateSignatures(
_vault,
_cancelHash,
_signature,
_sig
), "KR: Invalid Signatures"
);
removeQueue(_vault, _actionHash);
emit ActionCancelled(_vault);
}
| 16,575,456 | [
1,
10996,
87,
279,
2492,
1492,
1703,
12234,
18,
225,
389,
26983,
1021,
1018,
9229,
18,
225,
389,
892,
1021,
501,
364,
326,
18874,
329,
2492,
18,
225,
389,
12824,
1021,
7448,
1399,
358,
5309,
16033,
28444,
18,
225,
389,
8195,
1021,
3372,
3577,
358,
1954,
3755,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
3755,
12,
203,
3639,
1758,
389,
26983,
16,
203,
3639,
1731,
745,
892,
389,
892,
16,
203,
3639,
2254,
5034,
389,
12824,
16,
203,
3639,
1731,
3778,
389,
8195,
203,
565,
262,
7010,
3639,
3903,
7010,
565,
288,
203,
3639,
1731,
1578,
389,
1128,
2310,
273,
14167,
2310,
24899,
26983,
16,
374,
16,
389,
892,
16,
389,
12824,
1769,
203,
3639,
1731,
1578,
389,
10996,
2310,
273,
14167,
2310,
24899,
26983,
16,
374,
16,
315,
20,
92,
3113,
389,
12824,
1769,
203,
3639,
2583,
12,
291,
1803,
21039,
24899,
26983,
16,
389,
1128,
2310,
3631,
315,
47,
54,
30,
1962,
1651,
8863,
203,
3639,
9249,
389,
7340,
273,
12006,
2183,
3705,
23918,
24899,
26983,
16,
389,
892,
1769,
203,
3639,
2583,
12,
203,
5411,
1954,
23918,
12,
203,
7734,
389,
26983,
16,
203,
7734,
389,
10996,
2310,
16,
203,
7734,
389,
8195,
16,
203,
7734,
389,
7340,
203,
5411,
262,
16,
315,
47,
54,
30,
1962,
4383,
2790,
6,
203,
3639,
11272,
203,
3639,
1206,
3183,
24899,
26983,
16,
389,
1128,
2310,
1769,
203,
3639,
3626,
4382,
21890,
24899,
26983,
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
] |
// SPDX-License-Identifier: MIT
// Copyright (C) 2020, 2021, 2022 [email protected]
// Copyright (C) 2020, 2021, 2022 Swap.Pet
// 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.4.0;
/// @title Pegging WETH Interface of Swap.Pet
/// @author Swap.Pet
/// @notice Unlocks additional features for Wrapped Ether/WETH to interact with
/// contracts that use WETH transparently as ETH. Approve this contract
/// to spend WETH to use.
/// @dev The assumption is that user wants to use ETH and avoid unnecessary
/// approvals, but ERC20 is required to interact with many protocols.
/// This contract enables user to interact with protocols consuming ERC20
/// without additional approvals.
interface IPETH {
/// @notice Returns the WETH contract that this PETH contract uses.
/// @dev Returns the WETH contract that this PETH contract uses.
/// @return the WETH contract used by this contract.
function weth() external view returns (address payable);
/// @notice Deposits ETH sent to the contract, and transfers additional WETH from the caller,
/// and then approves and calls another contract `to` with data `data`.
/// @dev Use this method to spend a combination of ETH and WETH as WETH. Refunds any unspent WETH to the caller as
/// ETH. Note that either `amount`(ETH) or `msg.value`(WETH) may be 0, but not both.
/// @param amount The amount to transfer from the caller to this contract and approve for the `to` address, or 0.
/// @param to The address to approve and call after minting PETH
/// @param data The data to forward to the contract after minting PETH
function depositAndTransferFromThenCall(uint amount, address to, bytes calldata data) external payable;
/// @notice Unwrap and forward all WETH held by the contract to the given address. This should never be called
/// directly, but rather as a callback from a contract call that results in sending WETH to this contract.
/// @dev Use this method as a callback from other contracts to unwrap WETH before forwarding to the user.
/// @param to The address that should receive the unwrapped ETH.
function withdrawTo(address payable to) external;
}
| @title Pegging WETH Interface of Swap.Pet @author Swap.Pet @notice Unlocks additional features for Wrapped Ether/WETH to interact with contracts that use WETH transparently as ETH. Approve this contract to spend WETH to use. @dev The assumption is that user wants to use ETH and avoid unnecessary approvals, but ERC20 is required to interact with many protocols. This contract enables user to interact with protocols consuming ERC20 without additional approvals. | interface IPETH {
function weth() external view returns (address payable);
function depositAndTransferFromThenCall(uint amount, address to, bytes calldata data) external payable;
function withdrawTo(address payable to) external;
}
| 2,518,669 | [
1,
52,
1332,
1998,
678,
1584,
44,
6682,
434,
12738,
18,
52,
278,
225,
12738,
18,
52,
278,
225,
3967,
87,
3312,
4467,
364,
24506,
512,
1136,
19,
59,
1584,
44,
358,
16592,
598,
377,
20092,
716,
999,
678,
1584,
44,
17270,
715,
487,
512,
2455,
18,
1716,
685,
537,
333,
6835,
377,
358,
17571,
225,
678,
1584,
44,
358,
999,
18,
225,
1021,
24743,
353,
716,
729,
14805,
358,
999,
512,
2455,
471,
4543,
19908,
377,
6617,
4524,
16,
1496,
4232,
39,
3462,
353,
1931,
358,
16592,
598,
4906,
16534,
18,
377,
1220,
6835,
19808,
729,
358,
16592,
598,
16534,
27815,
4232,
39,
3462,
377,
2887,
3312,
6617,
4524,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
5831,
467,
1423,
2455,
288,
203,
565,
445,
341,
546,
1435,
3903,
1476,
1135,
261,
2867,
8843,
429,
1769,
203,
203,
565,
445,
443,
1724,
1876,
5912,
1265,
20112,
1477,
12,
11890,
3844,
16,
1758,
358,
16,
1731,
745,
892,
501,
13,
3903,
8843,
429,
31,
203,
203,
565,
445,
598,
9446,
774,
12,
2867,
8843,
429,
358,
13,
3903,
31,
203,
203,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig) public pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
//Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
}
/**
* @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;
}
}
/*
This is a token wallet contract
Store your tokens in this contract to give them super powers
Tokens can be spent from the contract with only an ecSignature from the owner - onchain approve is not needed
*/
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 ERC918Interface {
function totalSupply() public constant returns (uint);
function getMiningDifficulty() public constant returns (uint);
function getMiningTarget() public constant returns (uint);
function getMiningReward() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
}
contract MiningKingInterface {
function getMiningKing() public returns (address);
function transferKing(address newKing) public;
function mint(uint256 nonce, bytes32 challenge_digest) returns (bool);
event TransferKing(address from, address to);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
contract LavaWallet {
using SafeMath for uint;
// balances[tokenContractAddress][EthereumAccountAddress] = 0
mapping(address => mapping (address => uint256)) balances;
//token => owner => spender : amount
mapping(address => mapping (address => mapping (address => uint256))) allowed;
//mapping(address => uint256) depositedTokens;
mapping(bytes32 => uint256) burnedSignatures;
address relayKingContract;
event Deposit(address token, address user, uint amount, uint balance);
event Withdraw(address token, address user, uint amount, uint balance);
event Transfer(address indexed from, address indexed to,address token, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender,address token, uint tokens);
function LavaWallet(address relayKingContractAddress ) public {
relayKingContract = relayKingContractAddress;
}
//do not allow ether to enter
function() public payable {
revert();
}
//Remember you need pre-approval for this - nice with ApproveAndCall
function depositTokens(address from, address token, uint256 tokens ) public returns (bool success)
{
//we already have approval so lets do a transferFrom - transfer the tokens into this contract
if(!ERC20Interface(token).transferFrom(from, this, tokens)) revert();
balances[token][from] = balances[token][from].add(tokens);
// depositedTokens[token] = depositedTokens[token].add(tokens);
Deposit(token, from, tokens, balances[token][from]);
return true;
}
//No approve needed, only from msg.sender
function withdrawTokens(address token, uint256 tokens) public returns (bool success){
balances[token][msg.sender] = balances[token][msg.sender].sub(tokens);
if(!ERC20Interface(token).transfer(msg.sender, tokens)) revert();
Withdraw(token, msg.sender, tokens, balances[token][msg.sender]);
return true;
}
//Requires approval so it can be public
function withdrawTokensFrom( address from, address to,address token, uint tokens) public returns (bool success) {
balances[token][from] = balances[token][from].sub(tokens);
allowed[token][from][to] = allowed[token][from][to].sub(tokens);
if(!ERC20Interface(token).transfer(to, tokens)) revert();
Withdraw(token, from, tokens, balances[token][from]);
return true;
}
function balanceOf(address token,address user) public constant returns (uint) {
return balances[token][user];
}
function allowance(address token, address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[token][tokenOwner][spender];
}
//Can also be used to remove approval by using a 'tokens' value of 0. P.S. it makes no sense to do an ApproveTokensFrom
function approveTokens(address spender, address token, uint tokens) public returns (bool success) {
allowed[token][msg.sender][spender] = tokens;
Approval(msg.sender, token, spender, tokens);
return true;
}
///transfer tokens within the lava balances
//No approve needed, only from msg.sender
function transferTokens(address to, address token, uint tokens) public returns (bool success) {
balances[token][msg.sender] = balances[token][msg.sender].sub(tokens);
balances[token][to] = balances[token][to].add(tokens);
Transfer(msg.sender, token, to, tokens);
return true;
}
///transfer tokens within the lava balances
//Can be public because it requires approval
function transferTokensFrom( address from, address to,address token, uint tokens) public returns (bool success) {
balances[token][from] = balances[token][from].sub(tokens);
allowed[token][from][to] = allowed[token][from][to].sub(tokens);
balances[token][to] = balances[token][to].add(tokens);
Transfer(token, from, to, tokens);
return true;
}
//Nonce is the same thing as a 'check number'
//EIP 712
function getLavaTypedDataHash(bytes methodname, address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce) public constant returns (bytes32)
{
bytes32 hardcodedSchemaHash = 0x8fd4f9177556bbc74d0710c8bdda543afd18cc84d92d64b5620d5f1881dceb37; //with methodname
bytes32 typedDataHash = sha3(
hardcodedSchemaHash,
sha3(methodname,from,to,this,token,tokens,relayerReward,expires,nonce)
);
return typedDataHash;
}
function tokenApprovalWithSignature(bool requiresKing, address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, bytes32 sigHash, bytes signature) internal returns (bool success)
{
address recoveredSignatureSigner = ECRecovery.recover(sigHash,signature);
//make sure the signer is the depositor of the tokens
if(from != recoveredSignatureSigner) revert();
if(msg.sender != getRelayingKing() && requiresKing ) revert(); // you must be the 'king of the hill' to relay
//make sure the signature has not expired
if(block.number > expires) revert();
uint burnedSignature = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x1; //spent
if(burnedSignature != 0x0 ) revert();
//approve the relayer reward
allowed[token][from][msg.sender] = relayerReward;
Approval(from, token, msg.sender, relayerReward);
//transferRelayerReward
if(!transferTokensFrom(from, msg.sender, token, relayerReward)) revert();
//approve transfer of tokens
allowed[token][from][to] = tokens;
Approval(from, token, to, tokens);
return true;
}
function approveTokensFromAnyWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
bytes32 sigHash = getLavaTypedDataHash('anyApprove',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(false,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
return true;
}
function approveTokensFromKingWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
bytes32 sigHash = getLavaTypedDataHash('kingApprove',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(true,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
return true;
}
//the tokens remain in lava wallet
function transferTokensFromAnyWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash('anyTransfer',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(false,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
if(!transferTokensFrom( from, to, token, tokens)) revert();
return true;
}
//The tokens are withdrawn from the lava wallet and transferred into the To account
function transferTokensFromKingWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash('kingTransfer',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(true,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
if(!transferTokensFrom( from, to, token, tokens)) revert();
return true;
}
//the tokens remain in lava wallet
function withdrawTokensFromAnyWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash('anyWithdraw',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(false,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
if(!withdrawTokensFrom( from, to, token, tokens)) revert();
return true;
}
//The tokens are withdrawn from the lava wallet and transferred into the To account
function withdrawTokensFromKingWithSignature(address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash('kingWithdraw',from,to,token,tokens,relayerReward,expires,nonce);
if(!tokenApprovalWithSignature(true,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
if(!withdrawTokensFrom( from, to, token, tokens)) revert();
return true;
}
function burnSignature(bytes methodname, address from, address to, address token, uint256 tokens, uint256 relayerReward, uint256 expires, uint256 nonce, bytes signature) public returns (bool success)
{
bytes32 sigHash = getLavaTypedDataHash(methodname,from,to,token,tokens,relayerReward,expires,nonce);
address recoveredSignatureSigner = ECRecovery.recover(sigHash,signature);
//make sure the invalidator is the signer
if(recoveredSignatureSigner != from) revert();
//only the original packet owner can burn signature, not a relay
if(from != msg.sender) revert();
//make sure this signature has never been used
uint burnedSignature = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x2; //invalidated
if(burnedSignature != 0x0 ) revert();
return true;
}
//2 is burned
//1 is redeemed
function signatureBurnStatus(bytes32 digest) public view returns (uint)
{
return (burnedSignatures[digest]);
}
/*
Receive approval to spend tokens and perform any action all in one transaction
*/
function receiveApproval(address from, uint256 tokens, address token, bytes data) public returns (bool success) {
return depositTokens(from, token, tokens );
}
/*
Approve lava tokens for a smart contract and call the contracts receiveApproval method all in one fell swoop
One issue: the data is not being signed and so it could be manipulated
*/
function approveAndCall(bytes methodname, address from, address to, address token, uint256 tokens, uint256 relayerReward,
uint256 expires, uint256 nonce, bytes signature ) public {
bytes32 sigHash = getLavaTypedDataHash(methodname,from,to,token,tokens,relayerReward,expires,nonce);
bool requiresKing = getRequiresKing(methodname);
if(!tokenApprovalWithSignature(requiresKing,from,to,token,tokens,relayerReward,expires,sigHash,signature)) revert();
ApproveAndCallFallBack(to).receiveApproval(from, tokens, token, methodname);
}
function getRelayingKing() public returns (address)
{
return MiningKingInterface(relayKingContract).getMiningKing();
}
function getRequiresKing(bytes methodname) pure internal returns (bool)
{
return (bytesEqual(methodname,'kingTransfer') || bytesEqual(methodname,'kingWithdraw') || bytesEqual(methodname,'kingApprove'));
}
function bytesEqual(bytes b1,bytes b2) pure internal returns (bool)
{
if(b1.length != b2.length) return false;
for (uint i=0; i<b1.length; i++) {
if(b1[i] != b2[i]) return false;
}
return true;
}
} | Requires approval so it can be public | function withdrawTokensFrom( address from, address to,address token, uint tokens) public returns (bool success) {
balances[token][from] = balances[token][from].sub(tokens);
allowed[token][from][to] = allowed[token][from][to].sub(tokens);
if(!ERC20Interface(token).transfer(to, tokens)) revert();
Withdraw(token, from, tokens, balances[token][from]);
return true;
}
| 10,092,285 | [
1,
21671,
23556,
1427,
518,
848,
506,
1071,
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,
445,
598,
9446,
5157,
1265,
12,
1758,
628,
16,
1758,
358,
16,
2867,
1147,
16,
225,
2254,
2430,
13,
1071,
1135,
261,
6430,
2216,
13,
288,
203,
1377,
324,
26488,
63,
2316,
6362,
2080,
65,
273,
324,
26488,
63,
2316,
6362,
2080,
8009,
1717,
12,
7860,
1769,
203,
4202,
2935,
63,
2316,
6362,
2080,
6362,
869,
65,
273,
2935,
63,
2316,
6362,
2080,
6362,
869,
8009,
1717,
12,
7860,
1769,
203,
203,
1377,
309,
12,
5,
654,
39,
3462,
1358,
12,
2316,
2934,
13866,
12,
869,
16,
2430,
3719,
15226,
5621,
203,
203,
203,
1377,
3423,
9446,
12,
2316,
16,
628,
16,
2430,
16,
324,
26488,
63,
2316,
6362,
2080,
19226,
203,
1377,
327,
638,
31,
203,
225,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//SPDX-License-Identifier: MIT
pragma solidity ^0.7.6;
import "./IPLUG/IPLUGV1.sol";
import "./Pausable.sol";
import "./SafeMath.sol";
import "./SafeERC20.sol";
import "./IERC20.sol";
abstract contract stakeDaoVault {
function deposit(uint256 amount) external virtual;
function withdraw(uint256 shares) external virtual;
function balanceOf(address user) external virtual returns(uint256);
}
contract PLUGSTAKEV1 is IPLUGV1, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 private constant ONE_18 = 10**18;
address public override tokenWant = address(0x194eBd173F6cDacE046C53eACcE9B953F28411d1); //eursCRV
address public override tokenStrategy = address(0xCD6997334867728ba14d7922f72c893fcee70e84); //sdEURSCRV
address public override tokenReward; // ISLA
stakeDaoVault strategy = stakeDaoVault(tokenStrategy);
IERC20 iTokenWant = IERC20(tokenWant);
mapping (address => uint256) public tokenWantAmounts;
mapping (address => uint256) public tokenStrategyAmounts;
mapping (address => uint256) public tokenWantDonated;
uint256 usersTokenWant;
uint256 public plugLimit = uint256(50000).mul(ONE_18); // 50K plug limit
event PlugCharged(address user, uint256 amount, uint256 amountMinted);
event PlugDischarged(address user, uint256 userAmount, uint256 rewardForUSer, uint256 rewardForPlug);
event SentRewardToOutOne(address token, uint256 amount);
event SentRewardToOutTwo(address token, uint256 amount);
event Rebalance(uint256 amountEarned);
/**
* Charge plug staking token want into idle.
*/
function chargePlug(uint256 _amount) external override whenNotPaused() {
usersTokenWant = usersTokenWant.add(_amount);
require(usersTokenWant < plugLimit);
iTokenWant.safeTransferFrom(msg.sender, address(this), _amount);
require(_getPlugBalance(tokenWant) >= _amount);
uint256 vaultBefore = strategy.balanceOf(address(this));
strategy.deposit(_amount);
uint256 vaultAfter = strategy.balanceOf(address(this));
uint256 amountMinted = vaultAfter.sub(vaultBefore);
tokenStrategyAmounts[msg.sender] = tokenStrategyAmounts[msg.sender].add(amountMinted);
tokenWantAmounts[msg.sender] = tokenWantAmounts[msg.sender].add(_amount);
emit PlugCharged(msg.sender, _amount, amountMinted);
}
function dischargePlug(uint256 _plugPercentage) external override {
}
/**
* Internal function to discharge plug
*/
/*function _dischargePlug(uint256 _plugPercentage) internal {
require(_plugPercentage == 0 || _plugPercentage == 50 || _plugPercentage == 100);
uint256 userAmount = tokenWantAmounts[msg.sender];
require(userAmount > 0);
// transfer token want from IDLE to plug
uint256 amountRedeemed = strategy.redeemIdleToken(tokenStrategyAmounts[msg.sender]);
usersTokenWant = usersTokenWant.sub(userAmount);
// token want earned
uint256 tokenEarned;
uint256 rewardForUser;
uint256 rewardForPlug;
uint256 amountToDischarge;
// it should be always greater, added for safe
if (amountRedeemed <= userAmount) {
tokenEarned = 0;
userAmount = amountRedeemed;
} else {
tokenEarned = amountRedeemed.sub(userAmount);
rewardForUser = tokenEarned;
}
// calculate token earned percentage to donate into plug
if (_plugPercentage > 0 && tokenEarned > 0) {
rewardForPlug = tokenEarned;
rewardForUser = 0;
if (_plugPercentage == 50) {
rewardForPlug = rewardForPlug.div(2);
rewardForUser = tokenEarned.sub(rewardForPlug);
}
uint256 rewardLeft = _getPlugBalance(tokenReward);
if (rewardLeft > 0) {
uint256 rewardWithRate = rewardForPlug.mul(rewardRate).div(ONE_18);
_sendReward(rewardLeft, rewardWithRate);
}
tokenWantDonated[msg.sender] = tokenWantDonated[msg.sender].add(rewardForPlug);
}
// transfer tokenWant userAmount to user
amountToDischarge = userAmount.add(rewardForUser);
_dischargeUser(amountToDischarge);
emit PlugDischarged(msg.sender, userAmount, rewardForUser, rewardForPlug);
}*/
function upgradePlug(uint256 _nextLevelCap) external override {
}
function rebalancePlug() external override {
}
function _getPlugBalance(address _token) internal view returns(uint256) {
return IERC20(_token).balanceOf(address(this));
}
} | * Charge plug staking token want into idle./ | function chargePlug(uint256 _amount) external override whenNotPaused() {
usersTokenWant = usersTokenWant.add(_amount);
require(usersTokenWant < plugLimit);
iTokenWant.safeTransferFrom(msg.sender, address(this), _amount);
require(_getPlugBalance(tokenWant) >= _amount);
uint256 vaultBefore = strategy.balanceOf(address(this));
strategy.deposit(_amount);
uint256 vaultAfter = strategy.balanceOf(address(this));
uint256 amountMinted = vaultAfter.sub(vaultBefore);
tokenStrategyAmounts[msg.sender] = tokenStrategyAmounts[msg.sender].add(amountMinted);
tokenWantAmounts[msg.sender] = tokenWantAmounts[msg.sender].add(_amount);
emit PlugCharged(msg.sender, _amount, amountMinted);
}
| 12,536,015 | [
1,
17649,
15852,
384,
6159,
1147,
2545,
1368,
12088,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
13765,
1749,
637,
12,
11890,
5034,
389,
8949,
13,
3903,
3849,
1347,
1248,
28590,
1435,
288,
203,
3639,
3677,
1345,
59,
970,
273,
3677,
1345,
59,
970,
18,
1289,
24899,
8949,
1769,
203,
3639,
2583,
12,
5577,
1345,
59,
970,
411,
15852,
3039,
1769,
203,
203,
3639,
277,
1345,
59,
970,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
3639,
2583,
24899,
588,
1749,
637,
13937,
12,
2316,
59,
970,
13,
1545,
389,
8949,
1769,
203,
203,
3639,
2254,
5034,
9229,
4649,
273,
6252,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
6252,
18,
323,
1724,
24899,
8949,
1769,
203,
3639,
2254,
5034,
9229,
4436,
273,
6252,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
2254,
5034,
3844,
49,
474,
329,
273,
9229,
4436,
18,
1717,
12,
26983,
4649,
1769,
203,
540,
203,
3639,
1147,
4525,
6275,
87,
63,
3576,
18,
15330,
65,
273,
1147,
4525,
6275,
87,
63,
3576,
18,
15330,
8009,
1289,
12,
8949,
49,
474,
329,
1769,
203,
3639,
1147,
59,
970,
6275,
87,
63,
3576,
18,
15330,
65,
273,
1147,
59,
970,
6275,
87,
63,
3576,
18,
15330,
8009,
1289,
24899,
8949,
1769,
203,
3639,
3626,
3008,
637,
2156,
2423,
12,
3576,
18,
15330,
16,
389,
8949,
16,
3844,
49,
474,
329,
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
] |
pragma solidity ^0.4.26;
// Simple Options is a binary option smart contract. This is version 3 of the contract. There are a few improvements.
// Users are given a 1 hour window to determine whether the price of ETH will increase or decrease.
// Winners will divide a percentage of the house pot. That percentage is based on odds of winning.
// The lower the odds of winning, the higher the percentage the winners will receive.
// Odds of winning is equal to Winners Tickets / Total Tickets.
// Payout percent: 10% + 80% x (1 - Odds of Winning)
// Max payout is 90% of the pot but it is capped to total user contribution from each side (not combined)
// Only during the first 30 minutes of each round can users buy tickets.
// Once the time has expired, users can force the round to end which will trigger
// a payout from the house pot to the winning side and start a new round with the current price set as the starting price; however,
// if they don't, a cron job ran externally will automatically close the round.
// The user that closes the round will get the gasCost reimbursement from the house pot, upto 15 Gwei for gas price
// The price per ticket is fixed at 1/100th of the house pot but the minimum price is 0.0001 ETH and max is 1 ETH. Users can buy more than 1 ticket.
// The price Oracle for this contract is the Compound PriceOracle (0x2c9e6bdaa0ef0284eecef0e0cc102dcdeae4887e), which updates
// frequently when ETH price changes > 1%. cToken used is USDC (0x39aa39c021dfbae8fac545936693ac917d5e7563)
// The contract charges a fee that goes to the contract feeAddress upon winning. It is 5%. This fee is taken from the winners' payout
// If there is no contest, there are no fees.
// If at the end of the round, the price stays the same, there are no winners or losers. Everyone can withdraw their balance.
// If the round is not ended within 3 minutes after the deadline, the price is considered stale and there are no winners or
// losers. Everyone can withdraw their balance.
// If at the end of the round, there is no competition, the winners will receive at most 10% of the house pot split evenly between them.
contract Compound_ETHUSDC {
function getUnderlyingPrice(address cToken) external view returns (uint256);
}
contract Simple_Options_v3 {
// Administrator information
address public feeAddress; // This is the address of the person that collects the fees, nothing more, nothing less. It can be changed.
uint256 public feePercent = 5000; // This is the percent of the fee (5000 = 5.0%, 1 = 0.001%)
uint256 constant roundCutoff = 1800; // The cut-off time (in seconds) to submit a bet before the round ends. Currently 12 hours
uint256 constant roundLength = 3600; // The length of the round (in seconds)
address constant compoundOracleProxy = 0x2C9e6BDAA0EF0284eECef0e0Cc102dcDEaE4887e; // Contract address for the Compound price oracle proxy
address constant cUSDCAddress = 0x39AA39c021dfbaE8faC545936693aC917d5E7563;
// Different types of round Status
enum RoundStatus {
OPEN,
CLOSED,
STALEPRICE, // No winners due to price being too late
NOCONTEST // No winners
}
struct Round {
uint256 roundNum; // The round number
RoundStatus roundStatus; // The round status
uint256 startPriceWei; // ETH price at start of round
uint256 endPriceWei; // ETH price at end
uint256 startTime; // Unix seconds at start of round
uint256 endTime; // Unix seconds at end
uint256 endPotSize; // The contract pot size at the end of the round
uint256 totalCallTickets; // Tickets for expected price increase
uint256 totalCallPotWei; // Pot size for the users who believe in call
uint256 totalPutTickets; // Tickets for expected price decrease
uint256 totalPutPotWei; // Pot size for the users who believe in put
uint256 totalUsers; // Total users in this round
mapping (uint256 => address) userList;
mapping (address => User) users;
}
struct User {
uint256 numCallTickets;
uint256 numPutTickets;
uint256 callBalanceWei;
uint256 putBalanceWei;
}
mapping (uint256 => Round) roundList; // A mapping of all the rounds based on an integer
uint256 public currentRound = 0; // The current round
uint256 public currentPotSize = 0; // This is the size of the house pot, used to incentivise activity
event ChangedFeeAddress(address _newFeeAddress);
event FailedFeeSend(address _user, uint256 _amount);
event FeeSent(address _user, uint256 _amount);
event BoughtCallTickets(address _user, uint256 _ticketNum, uint256 _roundNum);
event BoughtPutTickets(address _user, uint256 _ticketNum, uint256 _roundNum);
event FailedPriceOracle();
event StartedNewRound(uint256 _roundNum);
constructor() public {
feeAddress = msg.sender; // Set the contract creator to the first feeAddress
}
// View function
// View round information
function viewRoundInfo(uint256 _numRound) public view returns (
uint256 _startPriceWei,
uint256 _endPriceWei,
uint256 _startTime,
uint256 _endTime,
uint256 _totalCallPotWei,
uint256 _totalPutPotWei,
uint256 _totalCallTickets,
uint256 _totalPutTickets,
RoundStatus _status,
uint256 _endPotSize
) {
assert(_numRound <= currentRound);
assert(_numRound >= 1);
Round memory _round = roundList[_numRound];
if(_numRound == currentRound) { _round.endPotSize = currentPotSize; } // For the current Round, current pot is its size
return (_round.startPriceWei, _round.endPriceWei, _round.startTime, _round.endTime, _round.totalCallPotWei, _round.totalPutPotWei, _round.totalCallTickets, _round.totalPutTickets, _round.roundStatus, _round.endPotSize);
}
// View user information that is round specific
function viewUserInfo(uint256 _numRound, address _userAddress) public view returns (
uint256 _numCallTickets,
uint256 _numPutTickets,
uint256 _balanceWei
) {
assert(_numRound <= currentRound);
assert(_numRound >= 1);
Round storage _round = roundList[_numRound];
User memory _user = _round.users[_userAddress];
uint256 balance = _user.callBalanceWei + _user.putBalanceWei;
return (_user.numCallTickets, _user.numPutTickets, balance);
}
// View the current round's ticket cost
function viewCurrentCost() public view returns (
uint256 _cost
) {
uint256 cost = calculateCost();
return (cost);
}
// Action functions
// Change contract fee address
function changeContractFeeAddress(address _newFeeAddress) public {
require (msg.sender == feeAddress); // Only the current feeAddress can change the feeAddress of the contract
feeAddress = _newFeeAddress; // Update the fee address
// Trigger event.
emit ChangedFeeAddress(_newFeeAddress);
}
// Add to the contract pot in case it becomes too small to incentivise
function addToHousePot() public payable {
require(msg.value > 0);
currentPotSize = currentPotSize + msg.value;
}
// This function creates a new round if the time is right (only after the endTime of the previous round) or if no rounds exist
// Anyone can request to start a new round, it is not priviledged
function startNewRound() public {
uint256 gasUsed = gasleft();
if(currentRound == 0){
// This is the first round of the contract
Round memory _newRound;
currentRound = currentRound + 1;
_newRound.roundNum = currentRound;
// Obtain the current price from the Maker Oracle
_newRound.startPriceWei = getOraclePrice(); // This function must return a price
// Set the timers up
_newRound.startTime = now;
_newRound.endTime = _newRound.startTime + roundLength; // 24 Hour rounds
roundList[currentRound] = _newRound;
emit StartedNewRound(currentRound);
}else if(currentRound > 0){
// The user wants to close the current round and start a new one
uint256 cTime = now;
uint256 feeAmount = 0;
Round storage _round = roundList[currentRound];
require( cTime >= _round.endTime ); // Cannot close a round unless the endTime is reached
// Obtain the current price from the Maker Oracle
_round.endPriceWei = getOraclePrice();
_round.endPotSize = currentPotSize; // The pot size will now be distributed
bool no_contest = false;
// If the price is stale, the current round has no losers or winners
if( cTime - 180 > _round.endTime){ // More than 3 minutes after round has ended, price is stale
no_contest = true;
_round.endTime = cTime;
_round.roundStatus = RoundStatus.STALEPRICE;
}
if(no_contest == false && _round.endPriceWei == _round.startPriceWei){
no_contest = true; // The price hasn't changed, so no one wins
_round.roundStatus = RoundStatus.NOCONTEST;
}
if(no_contest == false && _round.totalCallTickets == 0 && _round.totalPutTickets == 0){
no_contest = true; // There are no players in this round
_round.roundStatus = RoundStatus.NOCONTEST;
}
if(no_contest == false){
// Distribute winnings
feeAmount = distributeWinnings(_round);
// Close out the round completely which allows users to withdraw balance
_round.roundStatus = RoundStatus.CLOSED;
}
// Open up a new round using the endTime for the last round as the startTime
// and the endprice of the last round as the startprice
Round memory _nextRound;
currentRound = currentRound + 1;
_nextRound.roundNum = currentRound;
// The current price will be the previous round's end price
_nextRound.startPriceWei = _round.endPriceWei;
// Set the timers up
_nextRound.startTime = _round.endTime; // Set the start time to the previous round endTime
_nextRound.endTime = _nextRound.startTime + roundLength;
roundList[currentRound] = _nextRound;
// Send the fee if present
if(feeAmount > 0){
bool sentfee = feeAddress.send(feeAmount);
if(sentfee == false){
emit FailedFeeSend(feeAddress, feeAmount); // Create an event in case of fee sending failed, but don't stop ending the round
}else{
emit FeeSent(feeAddress, feeAmount); // Record that the fee was sent
}
}
emit StartedNewRound(currentRound);
}
// Pay back the caller of this function the gas fees from the house pot
// This is an expensive method so payback caller
gasUsed = gasUsed - gasleft() + 21000; // Cover the gas for the future send
uint256 gasCost = tx.gasprice; // This is the price of the gas in wei
if(gasCost > 15000000000) { gasCost = 15000000000; } // Gas price cannot be greater than 15 Gwei
gasCost = gasCost * gasUsed;
if(gasCost > currentPotSize) { gasCost = currentPotSize; } // Cannot be greater than the pot
currentPotSize = currentPotSize - gasCost;
if(gasCost > 0){
msg.sender.transfer(gasCost); // If this fails, revert the entire transaction, they will lose a lot of gas
}
}
// Buy some call tickets
function buyCallTickets() public payable {
buyTickets(0);
}
// Buy some put tickets
function buyPutTickets() public payable {
buyTickets(1);
}
// Withdraw from a previous round
// Cannot withdraw partial funds, all funds are withdrawn
function withdrawFunds(uint256 roundNum) public {
require( roundNum > 0 && roundNum < currentRound); // Can only withdraw from previous rounds
Round storage _round = roundList[roundNum];
require( _round.roundStatus != RoundStatus.OPEN ); // Round must be closed
User storage _user = _round.users[msg.sender];
uint256 balance = _user.callBalanceWei + _user.putBalanceWei;
require( _user.callBalanceWei + _user.putBalanceWei > 0); // Must have a balance to send out
_user.callBalanceWei = 0;
_user.putBalanceWei = 0;
msg.sender.transfer(balance); // Protected from re-entrancy
}
// Private functions
function calculateCost() private view returns (uint256 _weiCost){
uint256 cost = currentPotSize / 100;
cost = ceil(cost,100000000000000);
if(cost < 100000000000000) { cost = 100000000000000; } // Minimum cost of 0.0001 ETH
if(cost > 10000000000000000000) { cost = 10000000000000000000; } // Maximum cost of 1 ETH
return cost;
}
function calculateWinAmount(uint256 _fundSize, uint256 _winTickets, uint256 _totalTickets) private pure returns (uint256 _amount){
uint256 percent = 10000 + (80000 * (100000 - ((_winTickets * 100000) / _totalTickets))) / 100000; // 100% = 100 000, 1% = 1000
return (_fundSize * percent) / 100000;
}
function ceil(uint a, uint m) private pure returns (uint256 _ceil) {
return ((a + m - 1) / m) * m;
}
// Grabs the price from the Compound price oracle
function getOraclePrice() private view returns (uint256 _price){
Compound_ETHUSDC oracle = Compound_ETHUSDC(compoundOracleProxy);
uint256 usdcPrice = oracle.getUnderlyingPrice(cUSDCAddress); // This returns the price in relation to 1 ether
usdcPrice = usdcPrice / 1000000000000; // Normalize the price value
usdcPrice = 1000000000000000000000 / usdcPrice; // The precision level will be 3 decimal places
return (usdcPrice * 1000000000000000); // Now back to Wei units
}
// Distributes the players winnings from the house pot and returns the fee
// This function is needed to get around Ethereum's variable max
// Losers funds go to house pot for the next round
function distributeWinnings(Round storage _round) private returns (uint256 _fee){
// There are winners and losers
uint256 feeAmount = 0;
uint256 addAmount = 0;
uint256 it = 0;
uint256 rewardPerTicket = 0;
uint256 roundTotal = 0;
uint256 remainBalance = 0;
if(_round.endPriceWei > _round.startPriceWei){
// The calls have won the game
// Divide the house funds appropriately based on odds
roundTotal = calculateWinAmount(currentPotSize, _round.totalCallTickets, _round.totalCallTickets+_round.totalPutTickets);
// Cap the roundTotal is either the total contribution from the PutPotWei or CallPotWei, whichever is greater
if(roundTotal > _round.totalCallPotWei && roundTotal > _round.totalPutPotWei){
if(_round.totalCallPotWei > _round.totalPutPotWei){
roundTotal = _round.totalCallPotWei;
}else{
roundTotal = _round.totalPutPotWei;
}
}
if(_round.totalCallTickets > 0){
// There may not be call tickets, but still subtract the losers fee
currentPotSize = currentPotSize - roundTotal; // Take this balance from the pot
feeAmount = (roundTotal * feePercent) / 100000; // Fee is deducted from the winners amount
roundTotal = roundTotal - feeAmount;
rewardPerTicket = roundTotal / _round.totalCallTickets; // Split the pot among the winners
}
remainBalance = roundTotal;
for(it = 0; it < _round.totalUsers; it++){ // Go through each user in the round
User storage _user = _round.users[_round.userList[it]];
if(_user.numPutTickets > 0){
// We have some losing tickets, set our put balance to zero
_user.putBalanceWei = 0;
}
if(_user.numCallTickets > 0){
// We have some winning tickets, add to our call balance
addAmount = _user.numCallTickets * rewardPerTicket;
if(addAmount > remainBalance){addAmount = remainBalance;} // Cannot be greater than what is left
_user.callBalanceWei = _user.callBalanceWei + addAmount;
remainBalance = remainBalance - addAmount;
}
}
// Now add the losers funds to the remaining pot for the next round
currentPotSize = currentPotSize + _round.totalPutPotWei;
}else{
// The puts have won the game, price has decreased
// Divide the house funds appropriately based on odds
roundTotal = calculateWinAmount(currentPotSize, _round.totalPutTickets, _round.totalCallTickets+_round.totalPutTickets);
// Cap the roundTotal is either the total contribution from the PutPotWei or CallPotWei, whichever is greater
if(roundTotal > _round.totalCallPotWei && roundTotal > _round.totalPutPotWei){
if(_round.totalCallPotWei > _round.totalPutPotWei){
roundTotal = _round.totalCallPotWei;
}else{
roundTotal = _round.totalPutPotWei;
}
}
if(_round.totalPutTickets > 0){
// There may not be put tickets, but still subtract the losers fee
currentPotSize = currentPotSize - roundTotal; // Take this balance from the pot
feeAmount = (roundTotal * feePercent) / 100000; // Fee is deducted from the winners amount
roundTotal = roundTotal - feeAmount;
rewardPerTicket = roundTotal / _round.totalPutTickets; // Split the pot among the winners
}
remainBalance = roundTotal;
for(it = 0; it < _round.totalUsers; it++){ // Go through each user in the round
User storage _user2 = _round.users[_round.userList[it]];
if(_user2.numCallTickets > 0){
// We have some losing tickets, set our call balance to zero
_user2.callBalanceWei = 0;
}
if(_user2.numPutTickets > 0){
// We have some winning tickets, add to our put balance
addAmount = _user2.numPutTickets * rewardPerTicket;
if(addAmount > remainBalance){addAmount = remainBalance;} // Cannot be greater than what is left
_user2.putBalanceWei = _user2.putBalanceWei + addAmount;
remainBalance = remainBalance - addAmount;
}
}
// Now add the losers funds to the remaining pot for the next round
currentPotSize = currentPotSize + _round.totalCallPotWei;
}
return feeAmount;
}
function buyTickets(uint256 ticketType) private {
require( currentRound > 0 ); // There must be an active round ongoing
Round storage _round = roundList[currentRound];
uint256 endTime = _round.endTime;
uint256 currentTime = now;
require( currentTime <= endTime - roundCutoff); // Cannot buy a ticket after the cutoff time
uint256 currentCost = calculateCost(); // Calculate the price
require(msg.value % currentCost == 0); // The value must be a multiple of the cost
require(msg.value >= currentCost); // Must have some value
require(_round.totalUsers <= 1000); // Cannot have more than 1000 users per round
require(_round.roundStatus == RoundStatus.OPEN); // Round is still open, it should be
uint256 numTickets = msg.value / currentCost; // The user can buy multple tickets
// Check if user is in the mapping
User memory _user = _round.users[msg.sender];
if(_user.numCallTickets + _user.numPutTickets == 0){
// No tickets yet for user, new user
_round.userList[_round.totalUsers] = msg.sender;
_round.totalUsers = _round.totalUsers + 1;
}
if(ticketType == 0){
// Call ticket
_user.numCallTickets = _user.numCallTickets + numTickets;
_user.callBalanceWei = _user.callBalanceWei + msg.value;
_round.totalCallTickets = _round.totalCallTickets + numTickets;
_round.totalCallPotWei = _round.totalCallPotWei + msg.value;
emit BoughtCallTickets(msg.sender, numTickets, currentRound);
}else{
// Put ticket
_user.numPutTickets = _user.numPutTickets + numTickets;
_user.putBalanceWei = _user.putBalanceWei + msg.value;
_round.totalPutTickets = _round.totalPutTickets + numTickets;
_round.totalPutPotWei = _round.totalPutPotWei + msg.value;
emit BoughtPutTickets(msg.sender, numTickets, currentRound);
}
_round.users[msg.sender] = _user; // Add the user information to the game
}
}
| Cannot be greater than what is left
| if(addAmount > remainBalance){addAmount = remainBalance;} | 12,892,880 | [
1,
4515,
506,
6802,
2353,
4121,
353,
2002,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1850,
309,
12,
1289,
6275,
405,
7232,
13937,
15329,
1289,
6275,
273,
7232,
13937,
31,
97,
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
] |
./partial_match/8453/0x2c4A94874e4Dd52153CE2F2a4574b858928C1804/sources/TributaryRegistry.sol | @notice Adds a new singletone producer. @param producer new producer. | function addSingletonProducer(address producer)
public
override
onlyGovernance
{
singletonProducer[producer] = true;
}
| 16,765,420 | [
1,
3655,
279,
394,
4864,
1810,
476,
12608,
18,
225,
12608,
394,
12608,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
527,
19571,
12140,
12,
2867,
12608,
13,
203,
3639,
1071,
203,
3639,
3849,
203,
3639,
1338,
43,
1643,
82,
1359,
203,
565,
288,
203,
3639,
6396,
12140,
63,
11776,
2750,
65,
273,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0x23C6eEbeF6eaA19bA1c25B9F3F3e702271C3B49E/sources/LinkerPCS002.sol | * @dev Mint an NFT. @notice Owner only method. @param _owner Address to be minetd for the given NFT ID. @param _id ID of the token to be minted. @param _uri of the token to be minted. @param _artistId of the token to be minted. @param _duration of the auction for the token to be minted./ | function mint(
address _owner,
uint256 _id,
string calldata _uri,
string calldata _artistId,
address payable _beneficiary,
uint256 _duration,
uint256 _unit,
uint256 _minimumPrice,
address _keyAddress
) external onlyOwner {
require(_unit > 0, "The bidding unit (gap) should bigger than 0.");
super._mint(_owner, _id);
super._setTokenUri(_id, _uri);
_setArtistId(_id, _artistId);
_setStartedAt(_id);
_setDuration(_id, _duration);
_setHighestBidder(_id);
_setBeneficiary(_id, _beneficiary);
_setUnit(_id, _unit);
_setMinimumPrice(_id, _minimumPrice);
_setKeyAddress(_id, _keyAddress);
}
| 8,528,579 | [
1,
49,
474,
392,
423,
4464,
18,
225,
16837,
1338,
707,
18,
225,
389,
8443,
5267,
358,
506,
1131,
278,
72,
364,
326,
864,
423,
4464,
1599,
18,
225,
389,
350,
1599,
434,
326,
1147,
358,
506,
312,
474,
329,
18,
225,
389,
1650,
434,
326,
1147,
358,
506,
312,
474,
329,
18,
225,
389,
25737,
548,
434,
326,
1147,
358,
506,
312,
474,
329,
18,
225,
389,
8760,
434,
326,
279,
4062,
364,
326,
1147,
358,
506,
312,
474,
329,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
312,
474,
12,
203,
3639,
1758,
389,
8443,
16,
203,
3639,
2254,
5034,
389,
350,
16,
203,
3639,
533,
745,
892,
389,
1650,
16,
203,
3639,
533,
745,
892,
389,
25737,
548,
16,
203,
3639,
1758,
8843,
429,
389,
70,
4009,
74,
14463,
814,
16,
203,
3639,
2254,
5034,
389,
8760,
16,
203,
3639,
2254,
5034,
389,
4873,
16,
203,
3639,
2254,
5034,
389,
15903,
5147,
16,
203,
3639,
1758,
389,
856,
1887,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
2583,
24899,
4873,
405,
374,
16,
315,
1986,
324,
1873,
310,
2836,
261,
14048,
13,
1410,
18983,
2353,
374,
1199,
1769,
203,
3639,
2240,
6315,
81,
474,
24899,
8443,
16,
389,
350,
1769,
203,
3639,
2240,
6315,
542,
1345,
3006,
24899,
350,
16,
389,
1650,
1769,
203,
3639,
389,
542,
4411,
376,
548,
24899,
350,
16,
389,
25737,
548,
1769,
203,
3639,
389,
542,
9217,
861,
24899,
350,
1769,
203,
3639,
389,
542,
5326,
24899,
350,
16,
389,
8760,
1769,
203,
3639,
389,
542,
8573,
395,
17763,
765,
24899,
350,
1769,
203,
3639,
389,
542,
38,
4009,
74,
14463,
814,
24899,
350,
16,
389,
70,
4009,
74,
14463,
814,
1769,
203,
3639,
389,
542,
2802,
24899,
350,
16,
389,
4873,
1769,
203,
3639,
389,
542,
13042,
5147,
24899,
350,
16,
389,
15903,
5147,
1769,
203,
3639,
389,
542,
653,
1887,
24899,
350,
16,
389,
856,
1887,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
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;
/**
* @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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
/// @title SEKRETs
contract GeneScienceInterface {
/// @dev simply a boolean to indicate this is the contract we expect to be
function isGeneScience() public pure returns (bool);
/// @dev given genes of EtherDog 1 & 2, return a genetic combination - may have a random factor
/// @param genes1 genes of mom
/// @param genes2 genes of sire
/// @return the genes that are supposed to be passed down the child
function mixGenes(uint256 genes1, uint256 genes2, uint256 targetBlock) public returns (uint256);
}
/// @title A facet of EtherDogCore that manages special access privileges.
/// @author CybEye (http://www.cybeye.com/us/index.jsp)
/// @dev See the EtherDogCore contract documentation to understand how the various contract facets are arranged.
contract EtherDogACL {
// This facet controls access control for EtherDogs. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the EtherDogCore constructor.
//
// - The CFO: The CFO can withdraw funds from EtherDogCore and its auction contracts.
//
// - The COO: The COO can release gen0 EtherDogs to auction, and mint promo dogs.
//
// It should be noted that these roles are distinct without overlap in their access abilities, the
// abilities listed for each role above are exhaustive. In particular, while the CEO can assign any
// address to any role, the CEO address itself doesn't have the ability to act in those roles. This
// restriction is intentional so that we aren't tempted to use the CEO address frequently out of
// convenience. The less we use an address, the less likely it is that we somehow compromise the
// account.
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/// @dev 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 {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev 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 _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev 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) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Base contract for EtherDog. Holds all common structs, events and base variables.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the EtherDogCore contract documentation to understand how the various contract facets are arranged.
contract EtherDogBase is EtherDogACL {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new EtherDog comes into existence. This obviously
/// includes any time a EtherDog is created through the giveBirth method, but it is also called
/// when a new gen0 EtherDog is created.
event Birth(address owner, uint256 EtherDogId, uint256 matronId, uint256 sireId, uint256 genes, uint256 generation);
/// @dev Transfer event as defined in current draft of ERC721. Emitted every time a EtherDog
/// ownership is assigned, including births.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// @dev The main EtherDog struct. Every EtherDog in EtherDog is represented by a copy
/// of this structure, so great care was taken to ensure that it fits neatly into
/// exactly two 256-bit words. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct EtherDog {
// The EtherDog's genetic code is packed into these 256-bits, the format is
// sooper-sekret! A EtherDog's genes never change.
uint256 genes;
// The timestamp from the block when this EtherDog came into existence.
uint64 birthTime;
// The minimum timestamp after which this EtherDog can engage in breeding
// activities again. This same timestamp is used for the pregnancy
// timer (for matrons) as well as the siring cooldown.
uint64 cooldownEndBlock;
// The ID of the parents of this EtherDog, set to 0 for gen0 EtherDogs.
// Note that using 32-bit unsigned integers limits us to a "mere"
// 4 billion EtherDogs. This number might seem small until you realize
// that Ethereum currently has a limit of about 500 million
// transactions per year! So, this definitely won't be a problem
// for several years (even as Ethereum learns to scale).
uint32 matronId;
uint32 sireId;
// Set to the ID of the sire EtherDog for matrons that are pregnant,
// zero otherwise. A non-zero value here is how we know a EtherDog
// is pregnant. Used to retrieve the genetic material for the new
// EtherDog when the birth transpires.
uint32 siringWithId;
// Set to the index in the cooldown array (see below) that represents
// the current cooldown duration for this EtherDog. This starts at zero
// for gen0 EtherDogs, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding action, regardless
// of whether this EtherDog is acting as matron or sire.
uint16 cooldownIndex;
// The "generation number" of this EtherDog. EtherDogs minted by the CZ contract
// for sale are called "gen0" and have a generation number of 0. The
// generation number of all other EtherDogs is the larger of the two generation
// numbers of their parents, plus one.
// (i.e. max(matron.generation, sire.generation) + 1)
uint16 generation;
}
/*** CONSTANTS ***/
/// @dev A lookup table inEtherDoging the cooldown duration after any successful
/// breeding action, called "pregnancy time" for matrons and "siring cooldown"
/// for sires. Designed such that the cooldown roughly doubles each time a EtherDog
/// is bred, encouraging owners not to just keep breeding the same EtherDog over
/// and over again. Caps out at one week (a EtherDog can breed an unbounded number
/// of times, and the maximum cooldown is always seven days).
uint32[14] public cooldowns = [
uint32(1 minutes),
uint32(2 minutes),
uint32(5 minutes),
uint32(10 minutes),
uint32(30 minutes),
uint32(1 hours),
uint32(2 hours),
uint32(4 hours),
uint32(8 hours),
uint32(16 hours),
uint32(1 days),
uint32(2 days),
uint32(4 days),
uint32(7 days)
];
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
/*** STORAGE ***/
/// @dev An array containing the EtherDog struct for all EtherDogs in existence. The ID
/// of each EtherDog is actually an index into this array. Note that ID 0 is a negaEtherDog,
/// the unEtherDog, the mythical beast that is the parent of all gen0 EtherDogs. A bizarre
/// creature that is both matron and sire... to itself! Has an invalid genetic code.
/// In other words, EtherDog ID 0 is invalid... ;-)
EtherDog[] EtherDogs;
/// @dev A mapping from EtherDog IDs to the address that owns them. All EtherDogs have
/// some valid owner address, even gen0 EtherDogs are created with a non-zero owner.
mapping (uint256 => address) public EtherDogIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
/// @dev A mapping from EtherDogIDs to an address that has been approved to call
/// transferFrom(). Each EtherDog can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public EtherDogIndexToApproved;
/// @dev A mapping from EtherDogIDs to an address that has been approved to use
/// this EtherDog for siring via breedWith(). Each EtherDog can only have one approved
/// address for siring at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) public sireAllowedToAddress;
/// @dev The address of the ClockAuction contract that handles sales of EtherDogs. This
/// same contract handles both peer-to-peer sales as well as the gen0 sales which are
/// initiated every 15 minutes.
SaleClockAuction public saleAuction;
/// @dev The address of a custom ClockAuction subclassed contract that handles siring
/// auctions. Needs to be separate from saleAuction because the actions taken on success
/// after a sales and siring auction are quite different.
SiringClockAuction public siringAuction;
/// @dev Assigns ownership of a specific EtherDog to an address.
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// Since the number of EtherDogs is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
EtherDogIndexToOwner[_tokenId] = _to;
// When creating new EtherDogs _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// once the EtherDog is transferred also clear sire allowances
delete sireAllowedToAddress[_tokenId];
// clear any previously approved ownership exchange
delete EtherDogIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
/// @dev An internal method that creates a new EtherDog and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _matronId The EtherDog ID of the matron of this EtherDog (zero for gen0)
/// @param _sireId The EtherDog ID of the sire of this EtherDog (zero for gen0)
/// @param _generation The generation number of this EtherDog, must be computed by caller.
/// @param _genes The EtherDog's genetic code.
/// @param _owner The inital owner of this EtherDog, must be non-zero (except for the unEtherDog, ID 0)
function _createEtherDog(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createEtherDog() is already
// an expensive call (for storage), and it doesn't hurt to be especially careful
// to ensure our data structures are always valid.
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
// New EtherDog starts with the same cooldown as parent gen/2
uint16 cooldownIndex = uint16(_generation / 2);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
EtherDog memory _EtherDog = EtherDog({
genes: _genes,
birthTime: uint64(now),
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation)
});
uint256 newEtherDogId = EtherDogs.push(_EtherDog) - 1;
// It's probably never going to happen, 4 billion EtherDogs is A LOT, but
// let's just be 100% sure we never let this happen.
require(newEtherDogId == uint256(uint32(newEtherDogId)));
// emit the birth event
Birth(
_owner,
newEtherDogId,
uint256(_EtherDog.matronId),
uint256(_EtherDog.sireId),
_EtherDog.genes,
uint256(_EtherDog.generation)
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newEtherDogId);
return newEtherDogId;
}
/// @dev An internal method that creates a new EtherDog and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
/// @param _matronId The EtherDog ID of the matron of this EtherDog (zero for gen0)
/// @param _sireId The EtherDog ID of the sire of this EtherDog (zero for gen0)
/// @param _generation The generation number of this EtherDog, must be computed by caller.
/// @param _genes The EtherDog's genetic code.
/// @param _owner The inital owner of this EtherDog, must be non-zero (except for the unEtherDog, ID 0)
/// @param _time The birth time of EtherDog
/// @param _cooldownIndex The cooldownIndex of EtherDog
function _createEtherDogWithTime(
uint256 _matronId,
uint256 _sireId,
uint256 _generation,
uint256 _genes,
address _owner,
uint256 _time,
uint256 _cooldownIndex
)
internal
returns (uint)
{
// These requires are not strictly necessary, our calling code should make
// sure that these conditions are never broken. However! _createEtherDog() is already
// an expensive call (for storage), and it doesn't hurt to be especially careful
// to ensure our data structures are always valid.
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_generation == uint256(uint16(_generation)));
require(_time == uint256(uint64(_time)));
require(_cooldownIndex == uint256(uint16(_cooldownIndex)));
// Copy down EtherDog cooldownIndex
uint16 cooldownIndex = uint16(_cooldownIndex);
if (cooldownIndex > 13) {
cooldownIndex = 13;
}
EtherDog memory _EtherDog = EtherDog({
genes: _genes,
birthTime: uint64(_time),
cooldownEndBlock: 0,
matronId: uint32(_matronId),
sireId: uint32(_sireId),
siringWithId: 0,
cooldownIndex: cooldownIndex,
generation: uint16(_generation)
});
uint256 newEtherDogId = EtherDogs.push(_EtherDog) - 1;
// It's probably never going to happen, 4 billion EtherDogs is A LOT, but
// let's just be 100% sure we never let this happen.
require(newEtherDogId == uint256(uint32(newEtherDogId)));
// emit the birth event
Birth(
_owner,
newEtherDogId,
uint256(_EtherDog.matronId),
uint256(_EtherDog.sireId),
_EtherDog.genes,
uint256(_EtherDog.generation)
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newEtherDogId);
return newEtherDogId;
}
// Any C-level can fix how many seconds per blocks are currently observed.
function setSecondsPerBlock(uint256 secs) external onlyCLevel {
require(secs < cooldowns[0]);
secondsPerBlock = secs;
}
}
/// @title The external contract that is responsible for generating metadata for the EtherDogs,
/// it has one function that will return the data as bytes.
contract ERC721Metadata {
/// @dev Given a token Id, returns a byte array that is supposed to be converted into string.
function getMetadata(uint256 _tokenId, string) public pure returns (bytes32[4] buffer, uint256 count) {
if (_tokenId == 1) {
buffer[0] = "Hello World! :D";
count = 15;
} else if (_tokenId == 2) {
buffer[0] = "I would definitely choose a medi";
buffer[1] = "um length string.";
count = 49;
} else if (_tokenId == 3) {
buffer[0] = "Lorem ipsum dolor sit amet, mi e";
buffer[1] = "st accumsan dapibus augue lorem,";
buffer[2] = " tristique vestibulum id, libero";
buffer[3] = " suscipit varius sapien aliquam.";
count = 128;
}
}
}
/// @title The facet of the EtherDogs core contract that manages ownership, ERC-721 (draft) compliant.
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the EtherDogCore contract documentation to understand how the various contract facets are arranged.
contract EtherDogOwnership is EtherDogBase, ERC721 {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "EtherDogs";
string public constant symbol = "EDOG";
// The contract that will return EtherDog metadata
ERC721Metadata public erc721Metadata;
bytes4 constant InterfaceSignature_ERC165 =
bytes4(keccak256('supportsInterface(bytes4)'));
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. We implement
/// ERC-165 (obviously!) and ERC-721.
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
// DEBUG ONLY
//require((InterfaceSignature_ERC165 == 0x01ffc9a7) && (InterfaceSignature_ERC721 == 0x9a20483d));
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Set the address of the sibling contract that tracks metadata.
/// CEO only.
function setMetadataAddress(address _contractAddress) public onlyCEO {
erc721Metadata = ERC721Metadata(_contractAddress);
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular EtherDog.
/// @param _claimant the address we are validating against.
/// @param _tokenId EtherDog id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return EtherDogIndexToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular EtherDog.
/// @param _claimant the address we are confirming EtherDog is approved for.
/// @param _tokenId EtherDog id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return EtherDogIndexToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting EtherDogs on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
EtherDogIndexToApproved[_tokenId] = _approved;
}
/// @notice Returns the number of EtherDogs owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @notice Transfers a EtherDog to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// EtherDogs specifically) or your EtherDog may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the EtherDog to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any EtherDogs (except very briefly
// after a gen0 dog is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the auction contracts to prevent accidental
// misuse. Auction contracts should only take ownership of EtherDogs
// through the allow + transferFrom flow.
require(_to != address(saleAuction));
require(_to != address(siringAuction));
// You can only send your own dog.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific EtherDog via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the EtherDog that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a EtherDog owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the EtherDog to be transfered.
/// @param _to The address that should take ownership of the EtherDog. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the EtherDog to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any EtherDogs (except very briefly
// after a gen0 dog is created and before it goes on auction).
require(_to != address(this));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
require(_owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Returns the total number of EtherDogs currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return EtherDogs.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given EtherDog.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = EtherDogIndexToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all EtherDog IDs assigned to an address.
/// @param _owner The owner whose EtherDogs we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire EtherDog array looking for dogs belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalDogs = totalSupply();
uint256 resultIndex = 0;
// We count on the fact that all dogs have IDs starting at 1 and increasing
// sequentially up to the totalDog count.
uint256 dogId;
for (dogId = 1; dogId <= totalDogs; dogId++) {
if (EtherDogIndexToOwner[dogId] == _owner) {
result[resultIndex] = dogId;
resultIndex++;
}
}
return result;
}
}
/// @dev Adapted from memcpy() by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _memcpy(uint _dest, uint _src, uint _len) private view {
// Copy word-length chunks while possible
for(; _len >= 32; _len -= 32) {
assembly {
mstore(_dest, mload(_src))
}
_dest += 32;
_src += 32;
}
// Copy remaining bytes
uint256 mask = 256 ** (32 - _len) - 1;
assembly {
let srcpart := and(mload(_src), not(mask))
let destpart := and(mload(_dest), mask)
mstore(_dest, or(destpart, srcpart))
}
}
/// @dev Adapted from toString(slice) by @arachnid (Nick Johnson <[email protected]>)
/// This method is licenced under the Apache License.
/// Ref: https://github.com/Arachnid/solidity-stringutils/blob/2f6ca9accb48ae14c66f1437ec50ed19a0616f78/strings.sol
function _toString(bytes32[4] _rawBytes, uint256 _stringLength) private view returns (string) {
var outputString = new string(_stringLength);
uint256 outputPtr;
uint256 bytesPtr;
assembly {
outputPtr := add(outputString, 32)
bytesPtr := _rawBytes
}
_memcpy(outputPtr, bytesPtr, _stringLength);
return outputString;
}
/// @notice Returns a URI pointing to a metadata package for this token conforming to
/// ERC-721 (https://github.com/ethereum/EIPs/issues/721)
/// @param _tokenId The ID number of the EtherDog whose metadata should be returned.
function tokenMetadata(uint256 _tokenId, string _preferredTransport) external view returns (string infoUrl) {
require(erc721Metadata != address(0));
bytes32[4] memory buffer;
uint256 count;
(buffer, count) = erc721Metadata.getMetadata(_tokenId, _preferredTransport);
return _toString(buffer, count);
}
}
/// @title A facet of EtherDogCore that manages EtherDog siring, gestation, and birth.
/// @author Axiom Zen (https://www.axiomzen.co)
/// @dev See the EtherDogCore contract documentation to understand how the various contract facets are arranged.
contract EtherDogBreeding is EtherDogOwnership {
/// @dev The Pregnant event is fired when two dogs successfully breed and the pregnancy
/// timer begins for the matron.
event Pregnant(address owner, uint256 matronId, uint256 sireId, uint256 matronCooldownEndBlock, uint256 sireCooldownEndBlock);
/// @notice The minimum payment required to use breedWithAuto(). This fee goes towards
/// the gas cost paid by whatever calls giveBirth(), and can be dynamically updated by
/// the COO role as the gas price changes.
uint256 public autoBirthFee = 2 finney;
// Keeps track of number of pregnant EtherDogs.
uint256 public pregnantEtherDogs;
/// @dev The address of the sibling contract that is used to implement the sooper-sekret
/// genetic combination algorithm.
GeneScienceInterface public geneScience;
/// @dev Update the address of the genetic contract, can only be called by the CEO.
/// @param _address An address of a GeneScience contract instance to be used from this point forward.
function setGeneScienceAddress(address _address) external onlyCEO {
GeneScienceInterface candidateContract = GeneScienceInterface(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isGeneScience());
// Set the new contract address
geneScience = candidateContract;
}
/// @dev Checks that a given EtherDog is able to breed. Requires that the
/// current cooldown is finished (for sires) and also checks that there is
/// no pending pregnancy.
function _isReadyToBreed(EtherDog _dog) internal view returns (bool) {
// In addition to checking the cooldownEndBlock, we also need to check to see if
// the dog has a pending birth; there can be some period of time between the end
// of the pregnacy timer and the birth event.
return (_dog.siringWithId == 0) && (_dog.cooldownEndBlock <= uint64(block.number));
}
/// @dev Check if a sire has authorized breeding with this matron. True if both sire
/// and matron have the same owner, or if the sire has given siring permission to
/// the matron's owner (via approveSiring()).
function _isSiringPermitted(uint256 _sireId, uint256 _matronId) internal view returns (bool) {
address matronOwner = EtherDogIndexToOwner[_matronId];
address sireOwner = EtherDogIndexToOwner[_sireId];
// Siring is okay if they have same owner, or if the matron's owner was given
// permission to breed with this sire.
return (matronOwner == sireOwner || sireAllowedToAddress[_sireId] == matronOwner);
}
/// @dev Set the cooldownEndTime for the given EtherDog, based on its current cooldownIndex.
/// Also increments the cooldownIndex (unless it has hit the cap).
/// @param _dog A reference to the EtherDog in storage which needs its timer started.
function _triggerCooldown(EtherDog storage _dog) internal {
// Compute an estimation of the cooldown time in blocks (based on current cooldownIndex).
_dog.cooldownEndBlock = uint64((cooldowns[_dog.cooldownIndex]/secondsPerBlock) + block.number);
// Increment the breeding count, clamping it at 13, which is the length of the
// cooldowns array. We could check the array size dynamically, but hard-coding
// this as a constant saves gas. Yay, Solidity!
if (_dog.cooldownIndex < 13) {
_dog.cooldownIndex += 1;
}
}
/// @notice Grants approval to another user to sire with one of your EtherDogs.
/// @param _addr The address that will be able to sire with your EtherDog. Set to
/// address(0) to clear all siring approvals for this EtherDog.
/// @param _sireId A EtherDog that you own that _addr will now be able to sire with.
function approveSiring(address _addr, uint256 _sireId)
external
whenNotPaused
{
require(_owns(msg.sender, _sireId));
sireAllowedToAddress[_sireId] = _addr;
}
/// @dev Updates the minimum payment required for calling giveBirthAuto(). Can only
/// be called by the COO address. (This fee is used to offset the gas cost incurred
/// by the autobirth daemon).
function setAutoBirthFee(uint256 val) external onlyCOO {
autoBirthFee = val;
}
/// @dev Checks to see if a given EtherDog is pregnant and (if so) if the gestation
/// period has passed.
function _isReadyToGiveBirth(EtherDog _matron) private view returns (bool) {
return (_matron.siringWithId != 0) && (_matron.cooldownEndBlock <= uint64(block.number));
}
/// @notice Checks that a given EtherDog is able to breed (i.e. it is not pregnant or
/// in the middle of a siring cooldown).
/// @param _EtherDogId reference the id of the EtherDog, any user can inquire about it
function isReadyToBreed(uint256 _EtherDogId)
public
view
returns (bool)
{
require(_EtherDogId > 0);
EtherDog storage kit = EtherDogs[_EtherDogId];
return _isReadyToBreed(kit);
}
/// @dev Checks whether a EtherDog is currently pregnant.
/// @param _EtherDogId reference the id of the EtherDog, any user can inquire about it
function isPregnant(uint256 _EtherDogId)
public
view
returns (bool)
{
require(_EtherDogId > 0);
// A EtherDog is pregnant if and only if this field is set
return EtherDogs[_EtherDogId].siringWithId != 0;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair. DOES NOT
/// check ownership permissions (that is up to the caller).
/// @param _matron A reference to the EtherDog struct of the potential matron.
/// @param _matronId The matron's ID.
/// @param _sire A reference to the EtherDog struct of the potential sire.
/// @param _sireId The sire's ID
function _isValidMatingPair(
EtherDog storage _matron,
uint256 _matronId,
EtherDog storage _sire,
uint256 _sireId
)
private
view
returns(bool)
{
// A EtherDog can't breed with itself!
if (_matronId == _sireId) {
return false;
}
// EtherDogs can't breed with their parents.
if (_matron.matronId == _sireId || _matron.sireId == _sireId) {
return false;
}
if (_sire.matronId == _matronId || _sire.sireId == _matronId) {
return false;
}
// We can short circuit the sibling check (below) if either dog is
// gen zero (has a matron ID of zero).
if (_sire.matronId == 0 || _matron.matronId == 0) {
return true;
}
// EtherDogs can't breed with full or half siblings.
if (_sire.matronId == _matron.matronId || _sire.matronId == _matron.sireId) {
return false;
}
if (_sire.sireId == _matron.matronId || _sire.sireId == _matron.sireId) {
return false;
}
// Everything seems cool! Let's get DTF.
return true;
}
/// @dev Internal check to see if a given sire and matron are a valid mating pair for
/// breeding via auction (i.e. skips ownership and siring approval checks).
function _canBreedWithViaAuction(uint256 _matronId, uint256 _sireId)
internal
view
returns (bool)
{
EtherDog storage matron = EtherDogs[_matronId];
EtherDog storage sire = EtherDogs[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId);
}
/// @notice Checks to see if two dogs can breed together, including checks for
/// ownership and siring approvals. Does NOT check that both dogs are ready for
/// breeding (i.e. breedWith could still fail until the cooldowns are finished).
/// TODO: Shouldn't this check pregnancy and cooldowns?!?
/// @param _matronId The ID of the proposed matron.
/// @param _sireId The ID of the proposed sire.
function canBreedWith(uint256 _matronId, uint256 _sireId)
external
view
returns(bool)
{
require(_matronId > 0);
require(_sireId > 0);
EtherDog storage matron = EtherDogs[_matronId];
EtherDog storage sire = EtherDogs[_sireId];
return _isValidMatingPair(matron, _matronId, sire, _sireId) &&
_isSiringPermitted(_sireId, _matronId);
}
/// @dev Internal utility function to initiate breeding, assumes that all breeding
/// requirements have been checked.
function _breedWith(uint256 _matronId, uint256 _sireId) internal {
// Grab a reference to the EtherDogs from storage.
EtherDog storage sire = EtherDogs[_sireId];
EtherDog storage matron = EtherDogs[_matronId];
// Mark the matron as pregnant, keeping track of who the sire is.
matron.siringWithId = uint32(_sireId);
// Trigger the cooldown for both parents.
_triggerCooldown(sire);
_triggerCooldown(matron);
// Clear siring permission for both parents. This may not be strictly necessary
// but it's likely to avoid confusion!
delete sireAllowedToAddress[_matronId];
delete sireAllowedToAddress[_sireId];
// Every time a EtherDog gets pregnant, counter is incremented.
pregnantEtherDogs++;
// Emit the pregnancy event.
Pregnant(EtherDogIndexToOwner[_matronId], _matronId, _sireId, matron.cooldownEndBlock, sire.cooldownEndBlock);
}
/// @notice Breed a EtherDog you own (as matron) with a sire that you own, or for which you
/// have previously been given Siring approval. Will either make your dog pregnant, or will
/// fail entirely. Requires a pre-payment of the fee given out to the first caller of giveBirth()
/// @param _matronId The ID of the EtherDog acting as matron (will end up pregnant if successful)
/// @param _sireId The ID of the EtherDog acting as sire (will begin its siring cooldown if successful)
function breedWithAuto(uint256 _matronId, uint256 _sireId)
external
payable
whenNotPaused
{
// Checks for payment.
require(msg.value >= autoBirthFee);
// Caller must own the matron.
require(_owns(msg.sender, _matronId));
// Neither sire nor matron are allowed to be on auction during a normal
// breeding operation, but we don't need to check that explicitly.
// For matron: The caller of this function can't be the owner of the matron
// because the owner of a EtherDog on auction is the auction house, and the
// auction house will never call breedWith().
// For sire: Similarly, a sire on auction will be owned by the auction house
// and the act of transferring ownership will have cleared any oustanding
// siring approval.
// Thus we don't need to spend gas explicitly checking to see if either dog
// is on auction.
// Check that matron and sire are both owned by caller, or that the sire
// has given siring permission to caller (i.e. matron's owner).
// Will fail for _sireId = 0
require(_isSiringPermitted(_sireId, _matronId));
// Grab a reference to the potential matron
EtherDog storage matron = EtherDogs[_matronId];
// Make sure matron isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToBreed(matron));
// Grab a reference to the potential sire
EtherDog storage sire = EtherDogs[_sireId];
// Make sure sire isn't pregnant, or in the middle of a siring cooldown
require(_isReadyToBreed(sire));
// Test that these dogs are a valid mating pair.
require(_isValidMatingPair(
matron,
_matronId,
sire,
_sireId
));
// All checks passed, EtherDog gets pregnant!
_breedWith(_matronId, _sireId);
}
/// @notice Have a pregnant EtherDog give birth!
/// @param _matronId A EtherDog ready to give birth.
/// @return The EtherDog ID of the new EtherDog.
/// @dev Looks at a given EtherDog and, if pregnant and if the gestation period has passed,
/// combines the genes of the two parents to create a new EtherDog. The new EtherDog is assigned
/// to the current owner of the matron. Upon successful completion, both the matron and the
/// new EtherDog will be ready to breed again. Note that anyone can call this function (if they
/// are willing to pay the gas!), but the new EtherDog always goes to the mother's owner.
function giveBirth(uint256 _matronId)
external
whenNotPaused
returns(uint256)
{
// Grab a reference to the matron in storage.
EtherDog storage matron = EtherDogs[_matronId];
// Check that the matron is a valid dog.
require(matron.birthTime != 0);
// Check that the matron is pregnant, and that its time has come!
require(_isReadyToGiveBirth(matron));
// Grab a reference to the sire in storage.
uint256 sireId = matron.siringWithId;
EtherDog storage sire = EtherDogs[sireId];
// Determine the higher generation number of the two parents
uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
// Call the sooper-sekret gene mixing operation.
uint256 childGenes = geneScience.mixGenes(matron.genes, sire.genes, matron.cooldownEndBlock - 1);
// Make the new EtherDog!
address owner = EtherDogIndexToOwner[_matronId];
uint256 EtherDogId = _createEtherDog(_matronId, matron.siringWithId, parentGen + 1, childGenes, owner);
// Clear the reference to sire from the matron (REQUIRED! Having siringWithId
// set is what marks a matron as being pregnant.)
delete matron.siringWithId;
// Every time a EtherDog gives birth counter is decremented.
pregnantEtherDogs--;
// Send the balance fee to the person who made birth happen.
msg.sender.transfer(autoBirthFee);
// return the new EtherDog's ID
return EtherDogId;
}
}
/// @title Auction Core
/// @dev Contains models, variables, and internal methods for the auction.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuctionBase {
// Represents an auction on an NFT
struct Auction {
// Current owner of NFT
address seller;
// Price (in wei) at beginning of auction
uint128 startingPrice;
// Price (in wei) at end of auction
uint128 endingPrice;
// Duration (in seconds) of auction
uint64 duration;
// Time when auction started
// NOTE: 0 if this auction has been concluded
uint64 startedAt;
}
// Reference to contract tracking NFT ownership
ERC721 public nonFungibleContract;
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint256 public ownerCut;
// Map from token ID to their corresponding auction.
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startingPrice, uint256 endingPrice, uint256 duration);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
/// @dev Returns true if the claimant owns the token.
/// @param _claimant - Address claiming to own the token.
/// @param _tokenId - ID of token whose ownership to verify.
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return (nonFungibleContract.ownerOf(_tokenId) == _claimant);
}
/// @dev Escrows the NFT, assigning ownership to this contract.
/// Throws if the escrow fails.
/// @param _owner - Current owner address of token to escrow.
/// @param _tokenId - ID of token whose approval to verify.
function _escrow(address _owner, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transferFrom(_owner, this, _tokenId);
}
/// @dev Transfers an NFT owned by this contract to another address.
/// Returns true if the transfer succeeds.
/// @param _receiver - Address to transfer NFT to.
/// @param _tokenId - ID of token to transfer.
function _transfer(address _receiver, uint256 _tokenId) internal {
// it will throw if transfer fails
nonFungibleContract.transfer(_receiver, _tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires the
/// AuctionCreated event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint256 _tokenId, Auction _auction) internal {
// Require that all auctions have a duration of
// at least one minute. (Keeps our math from getting hairy!)
require(_auction.duration >= 1 minutes);
tokenIdToAuction[_tokenId] = _auction;
AuctionCreated(
uint256(_tokenId),
uint256(_auction.startingPrice),
uint256(_auction.endingPrice),
uint256(_auction.duration)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint256 _tokenId, address _seller) internal {
_removeAuction(_tokenId);
_transfer(_seller, _tokenId);
AuctionCancelled(_tokenId);
}
/// @dev Computes the price and transfers winnings.
/// Does NOT transfer ownership of token.
function _bid(uint256 _tokenId, uint256 _bidAmount)
internal
returns (uint256)
{
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
// Explicitly check that this auction is currently live.
// (Because of how Ethereum mappings work, we can't just count
// on the lookup above failing. An invalid _tokenId will just
// return an auction object that is all zeros.)
require(_isOnAuction(auction));
// Check that the bid is greater than or equal to the current price
uint256 price = _currentPrice(auction);
require(_bidAmount >= price);
// Grab a reference to the seller before the auction struct
// gets deleted.
address seller = auction.seller;
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy attack.
_removeAuction(_tokenId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate the auctioneer's cut.
// (NOTE: _computeCut() is guaranteed to return a
// value <= price, so this subtraction can't go negative.)
uint256 auctioneerCut = _computeCut(price);
uint256 sellerProceeds = price - auctioneerCut;
// NOTE: Doing a transfer() in the middle of a complex
// method like this is generally discouraged because of
// reentrancy attacks and DoS attacks if the seller is
// a contract with an invalid fallback function. We explicitly
// guard against reentrancy attacks by removing the auction
// before calling transfer(), and the only thing the seller
// can DoS is the sale of their own asset! (And if it's an
// accident, they can call cancelAuction(). )
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid. If the excess
// is anything worth worrying about, transfer it back to bidder.
// NOTE: We checked above that the bid amount is greater than or
// equal to the price so this cannot underflow.
uint256 bidExcess = _bidAmount - price;
// Return the funds. Similar to the previous transfer, this is
// not susceptible to a re-entry attack because the auction is
// removed before any transfers occur.
msg.sender.transfer(bidExcess);
// Tell the world!
AuctionSuccessful(_tokenId, price, msg.sender);
return price;
}
/// @dev Removes an auction from the list of open auctions.
/// @param _tokenId - ID of NFT on auction.
function _removeAuction(uint256 _tokenId) internal {
delete tokenIdToAuction[_tokenId];
}
/// @dev Returns true if the NFT is on auction.
/// @param _auction - Auction to check.
function _isOnAuction(Auction storage _auction) internal view returns (bool) {
return (_auction.startedAt > 0);
}
/// @dev Returns current price of an NFT on auction. Broken into two
/// functions (this one, that computes the duration from the auction
/// structure, and the other that does the price computation) so we
/// can easily test that the price computation works correctly.
function _currentPrice(Auction storage _auction)
internal
view
returns (uint256)
{
uint256 secondsPassed = 0;
// A bit of insurance against negative values (or wraparound).
// Probably not necessary (since Ethereum guarnatees that the
// now variable doesn't ever go backwards).
if (now > _auction.startedAt) {
secondsPassed = now - _auction.startedAt;
}
return _computeCurrentPrice(
_auction.startingPrice,
_auction.endingPrice,
_auction.duration,
secondsPassed
);
}
/// @dev Computes the current price of an auction. Factored out
/// from _currentPrice so we can run extensive unit tests.
/// When testing, make this function public and turn on
/// `Current price computation` test suite.
function _computeCurrentPrice(
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
uint256 _secondsPassed
)
internal
pure
returns (uint256)
{
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our public functions carefully cap the maximum values for
// time (at 64-bits) and currency (at 128-bits). _duration is
// also known to be non-zero (see the require() statement in
// _addAuction())
if (_secondsPassed >= _duration) {
// We've reached the end of the dynamic pricing portion
// of the auction, just return the end price.
return _endingPrice;
} else {
// Starting price can be higher than ending price (and often is!), so
// this delta can be negative.
int256 totalPriceChange = int256(_endingPrice) - int256(_startingPrice);
// This multiplication can't overflow, _secondsPassed will easily fit within
// 64-bits, and totalPriceChange will easily fit within 128-bits, their product
// will always fit within 256-bits.
int256 currentPriceChange = totalPriceChange * int256(_secondsPassed) / int256(_duration);
// currentPriceChange can be negative, but if so, will have a magnitude
// less that _startingPrice. Thus, this result will always end up positive.
int256 currentPrice = int256(_startingPrice) + currentPriceChange;
return uint256(currentPrice);
}
}
/// @dev Computes owner's cut of a sale.
/// @param _price - Sale price of NFT.
function _computeCut(uint256 _price) internal view returns (uint256) {
// NOTE: We don't use SafeMath (or similar) in this function because
// all of our entry functions carefully cap the maximum values for
// currency (at 128-bits), and ownerCut <= 10000 (see the require()
// statement in the ClockAuction constructor). The result of this
// function is always guaranteed to be <= _price.
return _price * ownerCut / 10000;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/// @title Clock auction for non-fungible tokens.
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract ClockAuction is Pausable, ClockAuctionBase {
/// @dev The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 = bytes4(0x9a20483d);
/// @dev Constructor creates a reference to the NFT ownership contract
/// and verifies the owner cut is in the valid range.
/// @param _nftAddress - address of a deployed contract implementing
/// the Nonfungible Interface.
/// @param _cut - percent cut the owner takes on each auction, must be
/// between 0-10,000.
function ClockAuction(address _nftAddress, uint256 _cut) public {
require(_cut <= 10000);
ownerCut = _cut;
ERC721 candidateContract = ERC721(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nonFungibleContract = candidateContract;
}
/// @dev Remove all Ether from the contract, which is the owner's cuts
/// as well as any Ether sent directly to the contract address.
/// Always transfers to the NFT contract, but can be called either by
/// the owner or the NFT contract.
function withdrawBalance() external {
address nftAddress = address(nonFungibleContract);
require(
msg.sender == owner ||
msg.sender == nftAddress
);
// We are using this boolean method to make sure that even if one fails it will still work
nftAddress.transfer(this.balance);
}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of time to move between starting
/// price and ending price (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
whenNotPaused
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(_owns(msg.sender, _tokenId));
_escrow(msg.sender, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Bids on an open auction, completing the auction and transferring
/// ownership of the NFT if enough Ether is supplied.
/// @param _tokenId - ID of token to bid on.
function bid(uint256 _tokenId)
external
payable
whenNotPaused
{
// _bid will throw if the bid or funds transfer fails
_bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
}
/// @dev Cancels an auction that hasn't been won yet.
/// Returns the NFT to original owner.
/// @notice This is a state-modifying function that can
/// be called while the contract is paused.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId)
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId, seller);
}
/// @dev Cancels an auction when the contract is paused.
/// Only the owner may do this, and NFTs are returned to
/// the seller. This should only be used in emergencies.
/// @param _tokenId - ID of the NFT on auction to cancel.
function cancelAuctionWhenPaused(uint256 _tokenId)
whenPaused
onlyOwner
external
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
_cancelAuction(_tokenId, auction.seller);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuction(uint256 _tokenId)
external
view
returns
(
address seller,
uint256 startingPrice,
uint256 endingPrice,
uint256 duration,
uint256 startedAt
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return (
auction.seller,
auction.startingPrice,
auction.endingPrice,
auction.duration,
auction.startedAt
);
}
/// @dev Returns the current price of an auction.
/// @param _tokenId - ID of the token price we are checking.
function getCurrentPrice(uint256 _tokenId)
external
view
returns (uint256)
{
Auction storage auction = tokenIdToAuction[_tokenId];
require(_isOnAuction(auction));
return _currentPrice(auction);
}
}
/// @title Reverse auction modified for siring
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SiringClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSiringAuctionAddress() call.
bool public isSiringClockAuction = true;
// Delegate constructor
function SiringClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction. Since this function is wrapped,
/// require sender to be EtherDogCore contract.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Places a bid for siring. Requires the sender
/// is the EtherDogCore contract because all bid methods
/// should be wrapped. Also returns the EtherDog to the
/// seller rather than the winner.
function bid(uint256 _tokenId)
external
payable
{
require(msg.sender == address(nonFungibleContract));
address seller = tokenIdToAuction[_tokenId].seller;
// _bid checks that token ID is valid and will throw if bid fails
_bid(_tokenId, msg.value);
// We transfer the EtherDog back to the seller, the winner will get
// the offspring
_transfer(seller, _tokenId);
}
}
/// @title Clock auction modified for sale of EtherDogs
/// @notice We omit a fallback function to prevent accidental sends to this contract.
contract SaleClockAuction is ClockAuction {
// @dev Sanity check that allows us to ensure that we are pointing to the
// right auction in our setSaleAuctionAddress() call.
bool public isSaleClockAuction = true;
// Tracks last 5 sale price of gen0 EtherDog sales
uint256 public gen0SaleCount;
uint256[5] public lastGen0SalePrices;
// Delegate constructor
function SaleClockAuction(address _nftAddr, uint256 _cut) public
ClockAuction(_nftAddr, _cut) {}
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
)
external
{
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startingPrice == uint256(uint128(_startingPrice)));
require(_endingPrice == uint256(uint128(_endingPrice)));
require(_duration == uint256(uint64(_duration)));
require(msg.sender == address(nonFungibleContract));
_escrow(_seller, _tokenId);
Auction memory auction = Auction(
_seller,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Updates lastSalePrice if seller is the nft contract
/// Otherwise, works the same as default bid method.
function bid(uint256 _tokenId)
external
payable
{
// _bid verifies token ID size
address seller = tokenIdToAuction[_tokenId].seller;
uint256 price = _bid(_tokenId, msg.value);
_transfer(msg.sender, _tokenId);
// If not a gen0 auction, exit
if (seller == address(nonFungibleContract)) {
// Track gen0 sale prices
lastGen0SalePrices[gen0SaleCount % 5] = price;
gen0SaleCount++;
}
}
function averageGen0SalePrice() external view returns (uint256) {
uint256 sum = 0;
for (uint256 i = 0; i < 5; i++) {
sum += lastGen0SalePrices[i];
}
return sum / 5;
}
}
/// @title Handles creating auctions for sale and siring of EtherDogs.
/// This wrapper of ReverseAuction exists only so that users can create
/// auctions with only one transaction.
contract EtherDogAuction is EtherDogBreeding {
// @notice The auction contract variables are defined in EtherDogBase to allow
// us to refer to them in EtherDogOwnership to prevent accidental transfers.
// `saleAuction` refers to the auction for gen0 and p2p sale of EtherDogs.
// `siringAuction` refers to the auction for siring rights of EtherDogs.
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionAddress(address _address) external onlyCEO {
SaleClockAuction candidateContract = SaleClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleAuction = candidateContract;
}
/// @dev Sets the reference to the siring auction.
/// @param _address - Address of siring contract.
function setSiringAuctionAddress(address _address) external onlyCEO {
SiringClockAuction candidateContract = SiringClockAuction(_address);
// NOTE: verify that a contract is what we expect - https://github.com/Lunyr/crowdsale-contracts/blob/cfadd15986c30521d8ba7d5b6f57b4fefcc7ac38/contracts/LunyrToken.sol#L117
require(candidateContract.isSiringClockAuction());
// Set the new contract address
siringAuction = candidateContract;
}
/// @dev Put a EtherDog up for auction.
/// Does some ownership trickery to create auctions in one tx.
function createSaleAuction(
uint256 _EtherDogId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If EtherDog is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _EtherDogId));
// Ensure the EtherDog is not pregnant to prevent the auction
// contract accidentally receiving ownership of the child.
// NOTE: the EtherDog IS allowed to be in a cooldown.
require(!isPregnant(_EtherDogId));
_approve(_EtherDogId, saleAuction);
// Sale auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the EtherDog.
saleAuction.createAuction(
_EtherDogId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Put a EtherDog up for auction to be sire.
/// Performs checks to ensure the EtherDog can be sired, then
/// delegates to reverse auction.
function createSiringAuction(
uint256 _EtherDogId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
external
whenNotPaused
{
// Auction contract checks input sizes
// If EtherDog is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _EtherDogId));
require(isReadyToBreed(_EtherDogId));
_approve(_EtherDogId, siringAuction);
// Siring auction throws if inputs are invalid and clears
// transfer and sire approval after escrowing the EtherDog.
siringAuction.createAuction(
_EtherDogId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Completes a siring auction by bidding.
/// Immediately breeds the winning matron with the sire on auction.
/// @param _sireId - ID of the sire on auction.
/// @param _matronId - ID of the matron owned by the bidder.
function bidOnSiringAuction(
uint256 _sireId,
uint256 _matronId
)
external
payable
whenNotPaused
{
// Auction contract checks input sizes
require(_owns(msg.sender, _matronId));
require(isReadyToBreed(_matronId));
require(_canBreedWithViaAuction(_matronId, _sireId));
// Define the current price of the auction.
uint256 currentPrice = siringAuction.getCurrentPrice(_sireId);
require(msg.value >= currentPrice + autoBirthFee);
// Siring auction will throw if the bid fails.
siringAuction.bid.value(msg.value - autoBirthFee)(_sireId);
_breedWith(uint32(_matronId), uint32(_sireId));
}
/// @dev Transfers the balance of the sale auction contract
/// to the EtherDogCore contract. We use two-step withdrawal to
/// prevent two transfer calls in the auction bid function.
function withdrawAuctionBalances() external onlyCLevel {
saleAuction.withdrawBalance();
siringAuction.withdrawBalance();
}
}
/// @title all functions related to creating EtherDogs
contract EtherDogMinting is EtherDogAuction {
// Limits the number of dogs the contract owner can ever create.
uint256 public constant DEFAULT_CREATION_LIMIT = 50000;
// Counts the number of dogs the contract owner has created.
uint256 public defaultCreatedCount;
/// @dev we can create EtherDogs with different generations. Only callable by COO
/// @param _genes The encoded genes of the EtherDog to be created, any value is accepted
/// @param _owner The future owner of the created EtherDog. Default to contract COO
/// @param _time The birth time of EtherDog
/// @param _cooldownIndex The cooldownIndex of EtherDog
function createDefaultGen0EtherDog(uint256 _genes, address _owner, uint256 _time, uint256 _cooldownIndex) external onlyCOO {
require(_time == uint256(uint64(_time)));
require(_cooldownIndex == uint256(uint16(_cooldownIndex)));
require(_time > 0);
require(_cooldownIndex >= 0 && _cooldownIndex <= 13);
address EtherDogOwner = _owner;
if (EtherDogOwner == address(0)) {
EtherDogOwner = cooAddress;
}
require(defaultCreatedCount < DEFAULT_CREATION_LIMIT);
defaultCreatedCount++;
_createEtherDogWithTime(0, 0, 0, _genes, EtherDogOwner, _time, _cooldownIndex);
}
/// @dev we can create EtherDogs with different generations. Only callable by COO
/// @param _matronId The EtherDog ID of the matron of this EtherDog
/// @param _sireId The EtherDog ID of the sire of this EtherDog
/// @param _genes The encoded genes of the EtherDog to be created, any value is accepted
/// @param _owner The future owner of the created EtherDog. Default to contract COO
/// @param _time The birth time of EtherDog
/// @param _cooldownIndex The cooldownIndex of EtherDog
function createDefaultEtherDog(uint256 _matronId, uint256 _sireId, uint256 _genes, address _owner, uint256 _time, uint256 _cooldownIndex) external onlyCOO {
require(_matronId == uint256(uint32(_matronId)));
require(_sireId == uint256(uint32(_sireId)));
require(_time == uint256(uint64(_time)));
require(_cooldownIndex == uint256(uint16(_cooldownIndex)));
require(_time > 0);
require(_cooldownIndex >= 0 && _cooldownIndex <= 13);
address EtherDogOwner = _owner;
if (EtherDogOwner == address(0)) {
EtherDogOwner = cooAddress;
}
require(_matronId > 0);
require(_sireId > 0);
// Grab a reference to the matron in storage.
EtherDog storage matron = EtherDogs[_matronId];
// Grab a reference to the sire in storage.
EtherDog storage sire = EtherDogs[_sireId];
// Determine the higher generation number of the two parents
uint16 parentGen = matron.generation;
if (sire.generation > matron.generation) {
parentGen = sire.generation;
}
_createEtherDogWithTime(_matronId, _sireId, parentGen + 1, _genes, EtherDogOwner, _time, _cooldownIndex);
}
}
/// @title EtherDogs: Collectible, breedable, and oh-so-adorable EtherDogs on the Ethereum blockchain.
/// @dev The main EtherDogs contract, keeps track of dogs so they don't wander around and get lost.
contract EtherDogCore is EtherDogMinting {
/* contract EtherDogCore { */
// This is the main EtherDogs contract. In order to keep our code seperated into logical sections,
// we've broken it up in two ways. First, we have several seperately-instantiated sibling contracts
// that handle auctions and our super-top-secret genetic combination algorithm. The auctions are
// seperate since their logic is somewhat complex and there's always a risk of subtle bugs. By keeping
// them in their own contracts, we can upgrade them without disrupting the main contract that tracks
// EtherDog ownership. The genetic combination algorithm is kept seperate so we can open-source all of
// the rest of our code without making it _too_ easy for folks to figure out how the genetics work.
// Don't worry, I'm sure someone will reverse engineer it soon enough!
//
// Secondly, we break the core contract into multiple files using inheritence, one for each major
// facet of functionality of CK. This allows us to keep related code bundled together while still
// avoiding a single giant file with everything in it. The breakdown is as follows:
//
// - EtherDogBase: This is where we define the most fundamental code shared throughout the core
// functionality. This includes our main data storage, constants and data types, plus
// internal functions for managing these items.
//
// - EtherDogAccessControl: This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO, CFO and COO.
//
// - EtherDogOwnership: This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
//
// - EtherDogBreeding: This file contains the methods necessary to breed EtherDogs together, including
// keeping track of siring offers, and relies on an external genetic combination contract.
//
// - EtherDogAuctions: Here we have the public methods for auctioning or bidding on EtherDogs or siring
// services. The actual auction functionality is handled in two sibling contracts (one
// for sales and one for siring), while auction creation and bidding is mostly mediated
// through this facet of the core contract.
//
// - EtherDogMinting: This final facet contains the functionality we use for creating new gen0 EtherDogs.
// We can make up to 5000 "promo" EtherDogs that can be given away (especially important when
// the community is new), and all others can only be created and then immediately put up
// for auction via an algorithmically determined starting price. Regardless of how they
// are created, there is a hard limit of 2400*12*12 gen0 EtherDogs. After that, it's all up to the
// community to breed, breed, breed!
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main EtherDogs smart contract instance.
function EtherDogCore() public {
// Starts paused.
paused = true;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is also the initial COO
cooAddress = msg.sender;
// start with the mythical EtherDog 0 - so we don't have generation-0 parent issues
_createEtherDog(0, 0, 0, uint256(-1), address(0));
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCEO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here, unless it's from one of the
/// two auction contracts. (Hopefully, we can prevent user accidents.)
function() external payable {
require(
msg.sender == address(saleAuction) ||
msg.sender == address(siringAuction)
);
}
/// @notice Returns all the relevant information about a specific EtherDog.
/// @param _id The ID of the EtherDog of interest.
function getEtherDog(uint256 _id)
external
view
returns (
bool isGestating,
bool isReady,
uint256 cooldownIndex,
uint256 nextActionAt,
uint256 siringWithId,
uint256 birthTime,
uint256 matronId,
uint256 sireId,
uint256 generation,
uint256 genes
) {
EtherDog storage dog = EtherDogs[_id];
// if this variable is 0 then it's not gestating
isGestating = (dog.siringWithId != 0);
isReady = (dog.cooldownEndBlock <= block.number);
cooldownIndex = uint256(dog.cooldownIndex);
nextActionAt = uint256(dog.cooldownEndBlock);
siringWithId = uint256(dog.siringWithId);
birthTime = uint256(dog.birthTime);
matronId = uint256(dog.matronId);
sireId = uint256(dog.sireId);
generation = uint256(dog.generation);
genes = dog.genes;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(saleAuction != address(0));
require(siringAuction != address(0));
require(geneScience != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the CFO to capture the balance available to the contract.
function withdrawBalance() external onlyCFO {
uint256 balance = this.balance;
// Subtract all the currently pregnant dogs we have, plus 1 of margin.
uint256 subtractFees = (pregnantEtherDogs + 1) * autoBirthFee;
if (balance > subtractFees) {
cfoAddress.transfer(balance - subtractFees);
}
}
} | @dev A mapping from owner address to count of tokens that address owns. Used internally inside balanceOf() to resolve ownership count. | mapping (address => uint256) ownershipTokenCount;
| 1,232,271 | [
1,
37,
2874,
628,
3410,
1758,
358,
1056,
434,
2430,
716,
1758,
29065,
18,
225,
10286,
12963,
4832,
11013,
951,
1435,
358,
2245,
23178,
1056,
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
] | [
1,
1,
1,
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,
202,
6770,
261,
2867,
516,
2254,
5034,
13,
23178,
1345,
1380,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import {Ownable} from "openzeppelin/contracts/access/Ownable.sol";
struct BatchConfig {
uint64 startBatchIndex; // the index of the first batch using this config
uint64 startBlockNumber; // the block number from which on this config is applicable
address[] keypers; // the keyper addresses
uint64 threshold; // the threshold parameter
uint64 batchSpan; // the duration of one batch in blocks
uint64 batchSizeLimit; // the maximum size of a batch in bytes
uint64 transactionSizeLimit; // the maximum size of each transaction in the batch in bytes
uint64 transactionGasLimit; // the maximum amount of gas each transaction may use
address feeReceiver; // the address receiving the collected fees
address targetAddress; // the address of the contract responsible of executing transactions
bytes4 targetFunctionSelector; // function of the target contract that executes transactions
uint64 executionTimeout; // the number of blocks after which execution can be skipped
}
/// @title A contract that manages `BatchConfig` objects.
/// @dev The config objects are stored in sequence, with configs applicable to later batches being
/// lined up behind configs applicable to earlier batches (according to
/// `config.startBlockNumber`). The contract owner is entitled to add or remove configs at the
/// end at will as long as a notice of at least `configChangeHeadsUpBlocks` is given.
/// @dev To add a new config, first populate the `nextConfig` object accordingly and then schedule
/// it with `scheduleNextConfig`.
contract ConfigContract is Ownable {
/// @notice The event emitted after a new config object has been scheduled.
/// @param numConfigs The new number of configs stored.
event ConfigScheduled(uint64 numConfigs);
/// @notice The event emitted after the owner has unscheduled one or more config objects.
/// @param numConfigs The new number of configs stored.
event ConfigUnscheduled(uint64 numConfigs);
// Stores all scheduled configs, plus the next config at the end
BatchConfig[] private configs;
uint64 public immutable configChangeHeadsUpBlocks;
constructor(uint64 headsUp) {
configs.push(_zeroConfig()); // guard
configs.push(_zeroConfig()); // next config
configChangeHeadsUpBlocks = headsUp;
}
function _zeroConfig() internal pure returns (BatchConfig memory) {
return
BatchConfig({
startBatchIndex: 0,
startBlockNumber: 0,
keypers: new address[](0),
threshold: 0,
batchSpan: 0,
batchSizeLimit: 0,
transactionSizeLimit: 0,
transactionGasLimit: 0,
feeReceiver: address(0),
targetAddress: address(0),
targetFunctionSelector: bytes4(0),
executionTimeout: 0
});
}
function numConfigs() public view returns (uint64) {
return uint64(configs.length) - 1; // exclude next config
}
function nextConfigIndex() public view returns (uint64) {
return uint64(configs.length) - 1;
}
function nextConfig() public view returns (BatchConfig memory) {
return configs[nextConfigIndex()];
}
function lastScheduledConfigIndex() public view returns (uint64) {
return uint64(configs.length) - 2;
}
function lastScheduledConfig() public view returns (BatchConfig memory) {
return configs[lastScheduledConfigIndex()];
}
/// @notice Get the index of the config for the batch with the given index.
/// @param batchIndex The index of the batch.
function configIndexForBatchIndex(uint64 batchIndex)
public
view
returns (uint64)
{
for (uint256 i = configs.length - 2; i >= 0; i--) {
if (configs[i].startBatchIndex <= batchIndex) {
return uint64(i);
}
}
assert(false);
return 0; // only for the linter
}
/// @notice Get the config for a certain batch.
/// @param batchIndex The index of the batch.
function configForBatchIndex(uint64 batchIndex)
public
view
returns (BatchConfig memory)
{
uint64 configIndex = configIndexForBatchIndex(batchIndex);
return configs[configIndex];
}
function configForConfigIndex(uint64 configIndex)
public
view
returns (BatchConfig memory)
{
return configs[configIndex];
}
//
// Config field getters
//
function configKeypers(uint64 configIndex, uint64 keyperIndex)
public
view
returns (address)
{
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].keypers[keyperIndex];
}
function configNumKeypers(uint64 configIndex) public view returns (uint64) {
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return uint64(configs[configIndex].keypers.length);
}
function configStartBatchIndex(uint64 configIndex)
public
view
returns (uint64)
{
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].startBatchIndex;
}
function configStartBlockNumber(uint64 configIndex)
public
view
returns (uint64)
{
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].startBlockNumber;
}
function configThreshold(uint64 configIndex) public view returns (uint64) {
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].threshold;
}
function configBatchSpan(uint64 configIndex) public view returns (uint64) {
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].batchSpan;
}
function configBatchSizeLimit(uint64 configIndex)
public
view
returns (uint64)
{
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].batchSizeLimit;
}
function configTransactionSizeLimit(uint64 configIndex)
public
view
returns (uint64)
{
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].transactionSizeLimit;
}
function configTransactionGasLimit(uint64 configIndex)
public
view
returns (uint64)
{
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].transactionGasLimit;
}
function configFeeReceiver(uint64 configIndex)
public
view
returns (address)
{
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].feeReceiver;
}
function configTargetAddress(uint64 configIndex)
public
view
returns (address)
{
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].targetAddress;
}
function configTargetFunctionSelector(uint64 configIndex)
public
view
returns (bytes4)
{
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].targetFunctionSelector;
}
function configExecutionTimeout(uint64 configIndex)
public
view
returns (uint64)
{
require(
configIndex < numConfigs(),
"ConfigContract: config index out of range"
);
return configs[configIndex].executionTimeout;
}
//
// next config setters
//
function nextConfigSetStartBatchIndex(uint64 startBatchIndex)
public
onlyOwner
{
configs[nextConfigIndex()].startBatchIndex = startBatchIndex;
}
function nextConfigSetStartBlockNumber(uint64 startBlockNumber)
public
onlyOwner
{
configs[nextConfigIndex()].startBlockNumber = startBlockNumber;
}
function nextConfigSetThreshold(uint64 threshold) public onlyOwner {
configs[nextConfigIndex()].threshold = threshold;
}
function nextConfigSetBatchSpan(uint64 batchSpan) public onlyOwner {
configs[nextConfigIndex()].batchSpan = batchSpan;
}
function nextConfigSetBatchSizeLimit(uint64 batchSizeLimit)
public
onlyOwner
{
configs[nextConfigIndex()].batchSizeLimit = batchSizeLimit;
}
function nextConfigSetTransactionSizeLimit(uint64 transactionSizeLimit)
public
onlyOwner
{
configs[nextConfigIndex()].transactionSizeLimit = transactionSizeLimit;
}
function nextConfigSetTransactionGasLimit(uint64 transactionGasLimit)
public
onlyOwner
{
configs[nextConfigIndex()].transactionGasLimit = transactionGasLimit;
}
function nextConfigSetFeeReceiver(address feeReceiver) public onlyOwner {
configs[nextConfigIndex()].feeReceiver = feeReceiver;
}
function nextConfigSetTargetAddress(address targetAddress)
public
onlyOwner
{
configs[nextConfigIndex()].targetAddress = targetAddress;
}
function nextConfigSetTargetFunctionSelector(bytes4 targetFunctionSelector)
public
onlyOwner
{
configs[nextConfigIndex()]
.targetFunctionSelector = targetFunctionSelector;
}
function nextConfigSetExecutionTimeout(uint64 executionTimeout)
public
onlyOwner
{
configs[nextConfigIndex()].executionTimeout = executionTimeout;
}
function nextConfigAddKeypers(address[] calldata newKeypers)
public
onlyOwner
{
require(
configs[nextConfigIndex()].keypers.length <=
type(uint64).max - newKeypers.length,
"ConfigContract: number of keypers exceeds uint64"
);
for (uint64 i = 0; i < newKeypers.length; i++) {
configs[nextConfigIndex()].keypers.push(newKeypers[i]);
}
}
function nextConfigRemoveKeypers(uint64 n) public onlyOwner {
uint256 currentLength = nextConfig().keypers.length;
if (n <= currentLength) {
for (uint64 i = 0; i < n; i++) {
configs[nextConfigIndex()].keypers.pop();
}
} else {
delete configs[nextConfigIndex()].keypers;
}
}
//
// nextConfig getters
//
function nextConfigKeypers(uint64 keyperIndex)
public
view
returns (address)
{
return nextConfig().keypers[keyperIndex];
}
function nextConfigNumKeypers() public view returns (uint64) {
return uint64(nextConfig().keypers.length);
}
function nextConfigStartBatchIndex() public view returns (uint64) {
return nextConfig().startBatchIndex;
}
function nextConfigStartBlockNumber() public view returns (uint64) {
return nextConfig().startBlockNumber;
}
function nextConfigThreshold() public view returns (uint64) {
return nextConfig().threshold;
}
function nextConfigBatchSpan() public view returns (uint64) {
return nextConfig().batchSpan;
}
function nextConfigBatchSizeLimit() public view returns (uint64) {
return nextConfig().batchSizeLimit;
}
function nextConfigTransactionSizeLimit() public view returns (uint64) {
return nextConfig().transactionSizeLimit;
}
function nextConfigTransactionGasLimit() public view returns (uint64) {
return nextConfig().transactionGasLimit;
}
function nextConfigFeeReceiver() public view returns (address) {
return nextConfig().feeReceiver;
}
function nextConfigTargetAddress() public view returns (address) {
return nextConfig().targetAddress;
}
function nextConfigTargetFunctionSelector() public view returns (bytes4) {
return nextConfig().targetFunctionSelector;
}
function nextConfigExecutionTimeout() public view returns (uint64) {
return nextConfig().executionTimeout;
}
//
// Scheduling
//
/// @notice Finalize the `nextConfig` object and add it to the end of the config sequence.
/// @notice `startBlockNumber` of the next config must be at least `configChangeHeadsUpBlocks`
/// blocks or the batch span of the current config in the future, whatever is greater.
/// @notice The transition between the next config and the config currently at the end of the
/// config sequence must be seamless, i.e., the batches must not be cut short.
function scheduleNextConfig() public onlyOwner {
require(
configs.length < type(uint64).max - 1,
"ConfigContract: number of configs exceeds uint64"
);
BatchConfig memory config1 = lastScheduledConfig();
BatchConfig memory config2 = nextConfig();
require(
config2.threshold <= config2.keypers.length,
"ConfigContract: threshold too large"
);
// check start block is not too early
uint64 headsUp = configChangeHeadsUpBlocks;
if (config1.batchSpan > headsUp) {
headsUp = config1.batchSpan;
}
uint64 earliestStart = uint64(block.number) + headsUp + 1;
require(
config2.startBlockNumber >= earliestStart,
"ConfigContract: start block too early"
);
// check transition is seamless
if (config1.batchSpan > 0) {
require(
config2.startBatchIndex > config1.startBatchIndex,
"ConfigContract: start batch index too small"
);
uint64 batchDelta = config2.startBatchIndex -
config1.startBatchIndex;
require(
config1.startBlockNumber + config1.batchSpan * batchDelta ==
config2.startBlockNumber,
"ConfigContract: config transition not seamless"
);
} else {
require(
config2.startBatchIndex == config1.startBatchIndex,
"ConfigContract: transition from inactive config with wrong start index"
);
}
configs.push(_zeroConfig());
emit ConfigScheduled(numConfigs());
}
/// @notice Remove configs from the end.
/// @param fromStartBlockNumber All configs with a start block number greater than or equal
/// to this will be removed.
/// @notice `fromStartBlockNumber` must be `configChangeHeadsUpBlocks` blocks in the future.
/// @notice This method can remove one or more configs. If no config would be removed, an error
/// is thrown.
/// @notice This invalidates the currently set next config.
function unscheduleConfigs(uint64 fromStartBlockNumber) public onlyOwner {
require(
fromStartBlockNumber > block.number + configChangeHeadsUpBlocks,
"ConfigContract: from start block too early"
);
uint64 lengthBefore = uint64(configs.length);
BatchConfig memory nextConfig_ = nextConfig();
configs.pop();
for (uint256 i = configs.length - 1; i > 0; i--) {
BatchConfig storage config = configs[i];
if (config.startBlockNumber >= fromStartBlockNumber) {
configs.pop();
} else {
break;
}
}
configs.push(nextConfig_); // add the next config again
require(
configs.length < lengthBefore,
"ConfigContract: no configs unscheduled"
);
emit ConfigUnscheduled(numConfigs());
}
function batchingActive(uint64 configIndex) public view returns (bool) {
return configs[configIndex].batchSpan > 0;
}
function batchBoundaryBlocks(uint64 configIndex, uint64 batchIndex)
public
view
returns (
uint64,
uint64,
uint64
)
{
uint64 startBlockNumber = configs[configIndex].startBlockNumber;
uint64 startBatchIndex = configs[configIndex].startBatchIndex;
uint64 batchSpan = configs[configIndex].batchSpan;
uint64 executionTimeout = configs[configIndex].executionTimeout;
assert(batchSpan > 0);
assert(batchIndex >= startBatchIndex);
uint64 relativeBatchIndex = batchIndex - startBatchIndex;
uint64 end = startBlockNumber +
relativeBatchIndex *
batchSpan +
batchSpan;
uint64 start = end - batchSpan;
if (relativeBatchIndex >= 1) {
start -= batchSpan;
}
uint64 timeout = end + executionTimeout;
return (start, end, timeout);
}
}
| the index of the first batch using this config
| uint64 startBatchIndex; | 7,290,791 | [
1,
5787,
770,
434,
326,
1122,
2581,
1450,
333,
642,
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,
2254,
1105,
787,
4497,
1016,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xA2276f75067ce77a62c5a9E18ebEac23Df6AbE2B/sources/project_/contracts/AvatarToken.sol | @dev See {IERC721Metadata-tokenURI}. | function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory uri = _baseURI();
return
bytes(uri).length > 0
? string(
abi.encodePacked(uri, _tokenId.toString())
)
: "";
}
| 1,908,554 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
2277,
17,
2316,
3098,
5496,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1147,
3098,
12,
11890,
5034,
389,
2316,
548,
13,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
2583,
24899,
1808,
24899,
2316,
548,
3631,
315,
654,
39,
27,
5340,
2277,
30,
3699,
843,
364,
1661,
19041,
1147,
8863,
203,
203,
3639,
533,
3778,
2003,
273,
389,
1969,
3098,
5621,
203,
203,
3639,
327,
203,
5411,
1731,
12,
1650,
2934,
2469,
405,
374,
203,
7734,
692,
533,
12,
203,
10792,
24126,
18,
3015,
4420,
329,
12,
1650,
16,
389,
2316,
548,
18,
10492,
10756,
203,
7734,
262,
203,
7734,
294,
1408,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45/sources/contracts/base/ApproveAndCall.sol | @title Approve and Call @notice Allows callers to approve the Uniswap V3 position manager from this contract, for any token, and then make calls into the position manager | abstract contract ApproveAndCall is IApproveAndCall, ImmutableState {
pragma solidity =0.7.6;
function tryApprove(address token, uint256 amount) private returns (bool) {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.approve.selector, positionManager, amount));
return success && (data.length == 0 || abi.decode(data, (bool)));
}
function getApprovalType(address token, uint256 amount) external override returns (ApprovalType) {
if (IERC20(token).allowance(address(this), positionManager) >= amount) return ApprovalType.NOT_REQUIRED;
if (tryApprove(token, type(uint256).max)) return ApprovalType.MAX;
if (tryApprove(token, type(uint256).max - 1)) return ApprovalType.MAX_MINUS_ONE;
require(tryApprove(token, 0));
if (tryApprove(token, type(uint256).max)) return ApprovalType.ZERO_THEN_MAX;
if (tryApprove(token, type(uint256).max - 1)) return ApprovalType.ZERO_THEN_MAX_MINUS_ONE;
revert();
}
function approveMax(address token) external payable override {
require(tryApprove(token, type(uint256).max));
}
function approveMaxMinusOne(address token) external payable override {
require(tryApprove(token, type(uint256).max - 1));
}
function approveZeroThenMax(address token) external payable override {
require(tryApprove(token, 0));
require(tryApprove(token, type(uint256).max));
}
function approveZeroThenMaxMinusOne(address token) external payable override {
require(tryApprove(token, 0));
require(tryApprove(token, type(uint256).max - 1));
}
function callPositionManager(bytes memory data) public payable override returns (bytes memory result) {
bool success;
(success, result) = positionManager.call(data);
if (!success) {
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
}
function callPositionManager(bytes memory data) public payable override returns (bytes memory result) {
bool success;
(success, result) = positionManager.call(data);
if (!success) {
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
}
function callPositionManager(bytes memory data) public payable override returns (bytes memory result) {
bool success;
(success, result) = positionManager.call(data);
if (!success) {
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
}
function balanceOf(address token) private view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
function mint(MintParams calldata params) external payable override returns (bytes memory result) {
return
callPositionManager(
abi.encodeWithSelector(
INonfungiblePositionManager.mint.selector,
INonfungiblePositionManager.MintParams({
token0: params.token0,
token1: params.token1,
fee: params.fee,
tickLower: params.tickLower,
tickUpper: params.tickUpper,
amount0Desired: balanceOf(params.token0),
amount1Desired: balanceOf(params.token1),
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
recipient: params.recipient,
})
)
);
}
function mint(MintParams calldata params) external payable override returns (bytes memory result) {
return
callPositionManager(
abi.encodeWithSelector(
INonfungiblePositionManager.mint.selector,
INonfungiblePositionManager.MintParams({
token0: params.token0,
token1: params.token1,
fee: params.fee,
tickLower: params.tickLower,
tickUpper: params.tickUpper,
amount0Desired: balanceOf(params.token0),
amount1Desired: balanceOf(params.token1),
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
recipient: params.recipient,
})
)
);
}
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
override
returns (bytes memory result)
{
return
callPositionManager(
abi.encodeWithSelector(
INonfungiblePositionManager.increaseLiquidity.selector,
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: params.tokenId,
amount0Desired: balanceOf(params.token0),
amount1Desired: balanceOf(params.token1),
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
})
)
);
}
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
override
returns (bytes memory result)
{
return
callPositionManager(
abi.encodeWithSelector(
INonfungiblePositionManager.increaseLiquidity.selector,
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: params.tokenId,
amount0Desired: balanceOf(params.token0),
amount1Desired: balanceOf(params.token1),
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
})
)
);
}
}
| 1,926,428 | [
1,
12053,
537,
471,
3049,
225,
25619,
19932,
358,
6617,
537,
326,
1351,
291,
91,
438,
776,
23,
1754,
3301,
628,
333,
6835,
16,
364,
1281,
1147,
16,
471,
1508,
1221,
4097,
1368,
326,
1754,
3301,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
17801,
6835,
1716,
685,
537,
1876,
1477,
353,
467,
12053,
537,
1876,
1477,
16,
7252,
1119,
288,
203,
683,
9454,
18035,
560,
273,
20,
18,
27,
18,
26,
31,
203,
565,
445,
775,
12053,
537,
12,
2867,
1147,
16,
2254,
5034,
3844,
13,
3238,
1135,
261,
6430,
13,
288,
203,
3639,
261,
6430,
2216,
16,
1731,
3778,
501,
13,
273,
203,
5411,
1147,
18,
1991,
12,
21457,
18,
3015,
1190,
4320,
12,
45,
654,
39,
3462,
18,
12908,
537,
18,
9663,
16,
1754,
1318,
16,
3844,
10019,
203,
3639,
327,
2216,
597,
261,
892,
18,
2469,
422,
374,
747,
24126,
18,
3922,
12,
892,
16,
261,
6430,
3719,
1769,
203,
565,
289,
203,
203,
565,
445,
336,
23461,
559,
12,
2867,
1147,
16,
2254,
5034,
3844,
13,
3903,
3849,
1135,
261,
23461,
559,
13,
288,
203,
3639,
309,
261,
45,
654,
39,
3462,
12,
2316,
2934,
5965,
1359,
12,
2867,
12,
2211,
3631,
1754,
1318,
13,
1545,
3844,
13,
327,
1716,
685,
1125,
559,
18,
4400,
67,
14977,
31,
203,
203,
3639,
309,
261,
698,
12053,
537,
12,
2316,
16,
618,
12,
11890,
5034,
2934,
1896,
3719,
327,
1716,
685,
1125,
559,
18,
6694,
31,
203,
3639,
309,
261,
698,
12053,
537,
12,
2316,
16,
618,
12,
11890,
5034,
2934,
1896,
300,
404,
3719,
327,
1716,
685,
1125,
559,
18,
6694,
67,
6236,
3378,
67,
5998,
31,
203,
203,
3639,
2583,
12,
698,
12053,
537,
12,
2316,
16,
374,
10019,
203,
203,
3639,
309,
261,
698,
12053,
537,
12,
2316,
16,
618,
12,
11890,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-04
*/
pragma solidity >=0.4.22 <0.6.0;
interface tokenRecipient {
function receiveApproval(address from, uint256 value, address token, bytes extraData) external;
}
//Actual token contract
contract ARTNANO{
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This generates a public event on the blockchain that will notify clients
event Approval(address indexed owner, address indexed spender, uint256 _value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constructor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
symbol = "ARNO";
name = "ART-NANO";
decimals = 18;
totalSupply = 50000000000000000000000000;
balanceOf[0x8817f003777293D25FADC1e4F320c395BDacE828] = totalSupply;
emit Transfer(address(0), 0x8817f003777293D25FADC1e4F320c395BDacE828, totalSupply); // Set the symbol for display purposes
}
function totalSupply() public constant returns (uint256) {
return totalSupply - balanceOf[address(0)];
}
/**
* Internal transfer, only can be called by this contract
*/
function transfer(address from, address to, uint256 value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(to != address(0x0));
// Check if the sender has enough
require(balanceOf[from] >= value);
// Check for overflows
require(balanceOf[to] + value >= balanceOf[to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[from] + balanceOf[to];
// Subtract from the sender
balanceOf[from] -= value;
// Add the same to the recipient
balanceOf[to] += value;
emit Transfer(from, to, value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[from] + balanceOf[to] == previousBalances);
}
/**
* Transfer tokens
*
* Send `value` tokens to `to` from your account
*
* @param to The address of the recipient
* @param value the amount to send
*/
function transfer(address to, uint256 value) public returns (bool success) {
transfer(msg.sender, to, value);
return true;
}
/**
* Transfer tokens from other address
*
* Send `value` tokens to `to` on behalf of `from`
*
* @param from The address of the sender
* @param to The address of the recipient
* @param value the amount to send
*/
function transferFrom(address from, address to, uint256 value) public returns (bool success) {
require(value <= allowance[from][msg.sender]); // Check allowance
allowance[from][msg.sender] -= value;
transfer(from, to, value);
return true;
}
/**
* Set allowance for other address
*
* Allows `spender` to spend no more than `value` tokens on your behalf
*
* @param spender The address authorized to spend
* @param value the max amount they can spend
*/
function approve(address spender, uint256 value) public
returns (bool success) {
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `spender` to spend no more than `value` tokens on your behalf, and then ping the contract about it
*
* @param spender The address authorized to spend
* @param value the max amount they can spend
* @param extraData some extra information to send to the approved contract
*/
function approveAndCall(address spender, uint256 value, bytes memory extraData)
public
returns (bool success) {
tokenRecipient _spender = tokenRecipient(spender);
if (approve(spender, value)) {
_spender.receiveApproval(msg.sender, value, address(this), extraData);
return true;
}
}
function giveBlockReward() public {
balanceOf[block.coinbase] += 1;
}
} | * Set allowance for other address and notify Allows `spender` to spend no more than `value` tokens on your behalf, and then ping the contract about it @param spender The address authorized to spend @param value the max amount they can spend @param extraData some extra information to send to the approved contract/ | function approveAndCall(address spender, uint256 value, bytes memory extraData)
public
returns (bool success) {
tokenRecipient _spender = tokenRecipient(spender);
if (approve(spender, value)) {
_spender.receiveApproval(msg.sender, value, address(this), extraData);
return true;
}
}
| 6,713,722 | [
1,
694,
1699,
1359,
364,
1308,
1758,
471,
5066,
25619,
1375,
87,
1302,
264,
68,
358,
17571,
1158,
1898,
2353,
1375,
1132,
68,
2430,
603,
3433,
12433,
6186,
16,
471,
1508,
10087,
326,
6835,
2973,
518,
225,
17571,
264,
1021,
1758,
10799,
358,
17571,
225,
460,
326,
943,
3844,
2898,
848,
17571,
225,
2870,
751,
2690,
2870,
1779,
358,
1366,
358,
326,
20412,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
565,
445,
6617,
537,
1876,
1477,
12,
2867,
17571,
264,
16,
2254,
5034,
460,
16,
1731,
3778,
2870,
751,
13,
203,
3639,
1071,
203,
3639,
1135,
261,
6430,
2216,
13,
288,
203,
3639,
1147,
18241,
389,
87,
1302,
264,
273,
1147,
18241,
12,
87,
1302,
264,
1769,
203,
3639,
309,
261,
12908,
537,
12,
87,
1302,
264,
16,
460,
3719,
288,
203,
5411,
389,
87,
1302,
264,
18,
18149,
23461,
12,
3576,
18,
15330,
16,
460,
16,
1758,
12,
2211,
3631,
2870,
751,
1769,
203,
5411,
327,
638,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x32234de40715073c70bf83415096e9e9265b6878
//Contract name: StandardCampaignFactory
//Balance: 0 Ether
//Verification Date: 2/8/2017
//Transacion Count: 4
// CODE STARTS HERE
/*
This file is part of WeiFund.
*/
/*
The core campaign contract interface. Used across all WeiFund standard campaign
contracts.
*/
pragma solidity ^0.4.4;
/// @title Campaign contract interface for WeiFund standard campaigns
/// @author Nick Dodson <[email protected]>
contract Campaign {
/// @notice the creater and operator of the campaign
/// @return the Ethereum standard account address of the owner specified
function owner() public constant returns(address) {}
/// @notice the campaign interface version
/// @return the version metadata
function version() public constant returns(string) {}
/// @notice the campaign name
/// @return contractual metadata which specifies the campaign name as a string
function name() public constant returns(string) {}
/// @notice use to determine the contribution method abi/structure
/// @return will return a string that is the exact contributeMethodABI
function contributeMethodABI() public constant returns(string) {}
/// @notice use to determine the contribution method abi
/// @return will return a string that is the exact contributeMethodABI
function refundMethodABI() public constant returns(string) {}
/// @notice use to determine the contribution method abi
/// @return will return a string that is the exact contributeMethodABI
function payoutMethodABI() public constant returns(string) {}
/// @notice use to determine the beneficiary destination for the campaign
/// @return the beneficiary address that will receive the campaign payout
function beneficiary() public constant returns(address) {}
/// @notice the block number at which the campaign fails or succeeds
/// @return the uint block number at which time the campaign expires
function expiry() public constant returns(uint256 blockNumber) {}
/// @notice the goal the campaign must reach in order for it to succeed
/// @return the campaign funding goal specified in wei as a uint256
function fundingGoal() public constant returns(uint256 amount) {}
/// @notice the maximum funding amount for this campaign
/// @return the campaign funding cap specified in wei as a uint256
function fundingCap() public constant returns(uint256 amount) {}
/// @notice the goal the campaign must reach in order for it to succeed
/// @return the campaign funding goal specified in wei as a uint256
function amountRaised() public constant returns(uint256 amount) {}
/// @notice the block number that the campaign was created
/// @return the campaign start block specified as a block number, uint256
function created() public constant returns(uint256 timestamp) {}
/// @notice the current stage the campaign is in
/// @return the campaign stage the campaign is in with uint256
function stage() public constant returns(uint256);
/// @notice if it supports it, return the contribution by ID
/// @return returns the contribution tx sender, value and time sent
function contributions(uint256 _contributionID) public constant returns(address _sender, uint256 _value, uint256 _time) {}
// Campaign events
event ContributionMade (address _contributor);
event RefundPayoutClaimed(address _payoutDestination, uint256 _payoutAmount);
event BeneficiaryPayoutClaimed (address _payoutDestination);
}
/*
This file is part of WeiFund.
*/
/*
The enhancer interface for the CampaignEnhancer contract.
*/
pragma solidity ^0.4.4;
/// @title The campaign enhancer interface contract for build enhancer contracts.
/// @author Nick Dodson <[email protected]>
contract Enhancer {
/// @notice enables the setting of the campaign, if any
/// @dev allow the owner to set the campaign
function setCampaign(address _campaign) public {}
/// @notice notate contribution
/// @param _sender The address of the contribution sender
/// @param _value The value of the contribution
/// @param _blockNumber The block number of the contribution
/// @param _amounts The specified contribution product amounts, if any
/// @return Whether or not the campaign is an early success after this contribution
/// @dev enables the notation of contribution data, and triggering of early success, if need be
function notate(address _sender, uint256 _value, uint256 _blockNumber, uint256[] _amounts) public returns (bool earlySuccess) {}
}
/*
This file is part of WeiFund.
*/
/*
A common Owned contract that contains properties for contract ownership.
*/
pragma solidity ^0.4.4;
/// @title A single owned campaign contract for instantiating ownership properties.
/// @author Nick Dodson <[email protected]>
contract Owned {
// only the owner can use this method
modifier onlyowner() {
if (msg.sender != owner) {
throw;
}
_;
}
// the owner property
address public owner;
}
/*
This file is part of WeiFund.
*/
/*
This is the standard claim contract interface. This used accross all claim
contracts. Claim contracts are used for the pickup of digital assets, such as tokens.
Note, a campaign enhancer could be a claim as well. This is our general
claim interface.
*/
pragma solidity ^0.4.4;
/// @title Claim contract interface.
/// @author Nick Dodson <[email protected]>
contract Claim {
/// @return returns the claim ABI solidity method for this claim
function claimMethodABI() constant public returns (string) {}
// the claim success event, used for whent he claim has successfully be used
event ClaimSuccess(address _sender);
}
/*
This file is part of WeiFund.
*/
/*
The balance claim is used for dispersing balances of refunds for standard
camaign contracts. Instead of the contract sending a balance directly to the
contributor, it will send the balance to a balancelciam contract.
*/
pragma solidity ^0.4.4;
/// @title The balance claim interface contract, used for defining balance claims.
/// @author Nick Dodson <[email protected]>
contract BalanceClaimInterface {
/// @dev used to claim balance of the balance claim
function claimBalance() public {}
}
/// @title The balance claim, used for sending balances owed to a claim contract.
/// @author Nick Dodson <[email protected]>
contract BalanceClaim is Owned, Claim, BalanceClaimInterface {
/// @notice receive funds
function () payable public {}
/// @dev the claim balance method, claim the balance then suicide the contract
function claimBalance() onlyowner public {
// self destruct and send all funds to the balance claim owner
selfdestruct(owner);
}
/// @notice The BalanceClaim constructor method
/// @param _owner the address of the balance claim owner
function BalanceClaim(address _owner) {
// specify the balance claim owner
owner = _owner;
}
// the claim method ABI metadata for user interfaces, written in standard
// solidity ABI method format
string constant public claimMethodABI = "claimBalance()";
}
/*
This file is part of WeiFund.
*/
/*
The private service registry is used in WeiFund factory contracts to register
generated service contracts, such as our WeiFund standard campaign and enhanced
standard campaign contracts. It is usually only inherited by other contracts.
*/
pragma solidity ^0.4.4;
/// @title Private Service Registry - used to register generated service contracts.
/// @author Nick Dodson <[email protected]>
contract PrivateServiceRegistryInterface {
/// @notice register the service '_service' with the private service registry
/// @param _service the service contract to be registered
/// @return the service ID 'serviceId'
function register(address _service) internal returns (uint256 serviceId) {}
/// @notice is the service in question '_service' a registered service with this registry
/// @param _service the service contract address
/// @return either yes (true) the service is registered or no (false) the service is not
function isService(address _service) public constant returns (bool) {}
/// @notice helps to get service address
/// @param _serviceId the service ID
/// @return returns the service address of service ID
function services(uint256 _serviceId) public constant returns (address _service) {}
/// @notice returns the id of a service address, if any
/// @param _service the service contract address
/// @return the service id of a service
function ids(address _service) public constant returns (uint256 serviceId) {}
event ServiceRegistered(address _sender, address _service);
}
contract PrivateServiceRegistry is PrivateServiceRegistryInterface {
modifier isRegisteredService(address _service) {
// does the service exist in the registry, is the service address not empty
if (services.length > 0) {
if (services[ids[_service]] == _service && _service != address(0)) {
_;
}
}
}
modifier isNotRegisteredService(address _service) {
// if the service '_service' is not a registered service
if (!isService(_service)) {
_;
}
}
function register(address _service)
internal
isNotRegisteredService(_service)
returns (uint serviceId) {
// create service ID by increasing services length
serviceId = services.length++;
// set the new service ID to the '_service' address
services[serviceId] = _service;
// set the ids store to link to the 'serviceId' created
ids[_service] = serviceId;
// fire the 'ServiceRegistered' event
ServiceRegistered(msg.sender, _service);
}
function isService(address _service)
public
constant
isRegisteredService(_service)
returns (bool) {
return true;
}
address[] public services;
mapping(address => uint256) public ids;
}
/*
This file is part of WeiFund.
*/
/*
This file is part of WeiFund.
*/
/*
Standard enhanced campaign for WeiFund. A generic crowdsale mechanism for
issuing and dispersing digital assets on Ethereum.
*/
pragma solidity ^0.4.4;
/*
Interfaces
*/
/*
Specified Contracts
*/
/// @title Standard Campaign -- enables generic crowdsales that disperse digital assets
/// @author Nick Dodson <[email protected]>
contract StandardCampaign is Owned, Campaign {
// the three possible states
enum Stages {
CrowdfundOperational,
CrowdfundFailure,
CrowdfundSuccess
}
// the campaign state machine enforcement
modifier atStage(Stages _expectedStage) {
// if the current state does not equal the expected one, throw
if (stage() != uint256(_expectedStage)) {
throw;
} else {
// continue with state changing operations
_;
}
}
// if the contribution is valid, then carry on with state changing operations
// notate the contribution with the enhancer, if the notation method
// returns true, then trigger an early success (e.g. token cap reached)
modifier validContribution() {
// if the msg value is zero or amount raised plus the curent message value
// is greater than the funding cap, then throw error
if (msg.value == 0
|| amountRaised + msg.value > fundingCap
|| amountRaised + msg.value < amountRaised) {
throw;
} else {
// carry on with state changing operations
_;
}
}
// if the contribution is a valid refund claim, then carry on with state
// changing operations
modifier validRefundClaim(uint256 _contributionID) {
// get the contribution data for the refund
Contribution refundContribution = contributions[_contributionID];
// if the refund has already been claimed or the refund sender is not the
// current message sender, throw error
if(refundsClaimed[_contributionID] == true // the refund for this contribution is not claimed
|| refundContribution.sender != msg.sender){ // the contribution sender is the msg.sender
throw;
} else {
// all is good, carry on with state changing operations
_;
}
}
// only the beneficiary can use the method with this modifier
modifier onlybeneficiary() {
if (msg.sender != beneficiary) {
throw;
} else {
_;
}
}
// allow for fallback function to be used to make contributions
function () public payable {
contributeMsgValue(defaultAmounts);
}
// the current campaign stage
function stage() public constant returns (uint256) {
// if current time is less than the expiry, the crowdfund is operational
if (block.number < expiry
&& earlySuccess == false
&& amountRaised < fundingCap) {
return uint256(Stages.CrowdfundOperational);
// if n >= e and aR < fG then the crowdfund is a failure
} else if(block.number >= expiry
&& earlySuccess == false
&& amountRaised < fundingGoal) {
return uint256(Stages.CrowdfundFailure);
// if n >= e and aR >= fG or aR >= fC or early success triggered
// then the crowdfund is a success (enhancers can trigger early success)
// early success is generally used for TokenCap enforcement
} else if((block.number >= expiry && amountRaised >= fundingGoal)
|| earlySuccess == true
|| amountRaised >= fundingCap) {
return uint256(Stages.CrowdfundSuccess);
}
}
// contribute message value if the contribution is valid and the campaign
// is in stage operational, allow for complex amounts to be transacted
function contributeMsgValue(uint256[] _amounts)
public // anyone can attempt to use this method
payable // the method is payable and can accept ether
atStage(Stages.CrowdfundOperational) // must be at stage operational, done before validContribution
validContribution() // contribution must be valid, stage check done first
returns (uint256 contributionID) {
// increase contributions array length by 1, set as contribution ID
contributionID = contributions.length++;
// store contribution data in the contributions array
contributions[contributionID] = Contribution({
sender: msg.sender,
value: msg.value,
created: block.number
});
// add the contribution ID to that senders address
contributionsBySender[msg.sender].push(contributionID);
// increase the amount raised by the message value
amountRaised += msg.value;
// fire the contribution made event
ContributionMade(msg.sender);
// notate the contribution with the campaign enhancer, if the notation
// method returns true, then trigger an early success
// the enahncer is treated as malicious here, and is thus wrapped in a
// conditional for saftey, note the enhancer may throw as well
if (enhancer.notate(msg.sender, msg.value, block.number, _amounts)) {
// set early success to true, note, it cannot be reversed once set to true
// also validContribution must be after atStage modifier
// so that early success is triggered after stage check, not before
// early success is used to trigger an early campaign success before the funding
// cap is reached. This is generally used for things like hitting the token cap
earlySuccess = true;
}
}
// payout the current balance to the beneficiary, if the crowdfund is in
// stage success
function payoutToBeneficiary() public onlybeneficiary() {
// additionally trigger early success, this will force the Success state
// forcing the success state keeps the contract state machine rigid
// and ensures other third-party contracts that look to this state
// that this contract is in state success
earlySuccess = true;
// send funds to the benerifiary
if (!beneficiary.send(this.balance)) {
throw;
} else {
// fire the BeneficiaryPayoutClaimed event
BeneficiaryPayoutClaimed(beneficiary);
}
}
// claim refund owed if you are a contributor and the campaign is in stage
// failure. Only valid claims will be fulfilled.
// will return the balance claim address where funds can be picked up by
// contributor. A BalanceClaim is used to further prevent re-entrancy.
function claimRefundOwed(uint256 _contributionID)
public
atStage(Stages.CrowdfundFailure) // in stage failure
validRefundClaim(_contributionID) // the claim is a valid refund claim
returns (address balanceClaim) { // return the balance claim address
// set claimed to true right away
refundsClaimed[_contributionID] = true;
// get the contribution data for that contribution ID
Contribution refundContribution = contributions[_contributionID];
// send funds to the newly created balance claim contract
balanceClaim = address(new BalanceClaim(refundContribution.sender));
// set refunds claim address
refundClaimAddress[_contributionID] = balanceClaim;
// send funds to the newly created balance claim contract
if (!balanceClaim.send(refundContribution.value)) {
throw;
}
// fire the refund payed out event
RefundPayoutClaimed(balanceClaim, refundContribution.value);
}
// the total number of valid contributions made to this campaign
function totalContributions() public constant returns (uint256 amount) {
return uint256(contributions.length);
}
// get the total number of contributions made a sender
function totalContributionsBySender(address _sender)
public
constant
returns (uint256 amount) {
return uint256(contributionsBySender[_sender].length);
}
// the contract constructor
function StandardCampaign(string _name,
uint256 _expiry,
uint256 _fundingGoal,
uint256 _fundingCap,
address _beneficiary,
address _owner,
address _enhancer) public {
// set the campaign name
name = _name;
// the campaign expiry in blocks
expiry = _expiry;
// the fundign goal in wei
fundingGoal = _fundingGoal;
// the campaign funding cap in wei
fundingCap = _fundingCap;
// the benerifiary address
beneficiary = _beneficiary;
// the owner or operator of the campaign
owner = _owner;
// the time the campaign was created
created = block.number;
// the campaign enhancer contract
enhancer = Enhancer(_enhancer);
}
// the Contribution data structure
struct Contribution {
// the contribution sender
address sender;
// the value of the contribution
uint256 value;
// the time the contribution was created
uint256 created;
}
// default amounts used
uint256[] defaultAmounts;
// campaign enhancer, usually for token notation
Enhancer public enhancer;
// the early success bool, used for triggering early success
bool public earlySuccess;
// the operator of the campaign
address public owner;
// the minimum amount of funds needed to be a success after expiry (in wei)
uint256 public fundingGoal;
// the maximum amount of funds that can be raised (in wei)
uint256 public fundingCap;
// the total amount raised by this campaign (in wei)
uint256 public amountRaised;
// the current campaign expiry (future block number)
uint256 public expiry;
// the time at which the campaign was created (in UNIX timestamp)
uint256 public created;
// the beneficiary of the funds raised, if the campaign is a success
address public beneficiary;
// the contributions data store, where all contributions are notated
Contribution[] public contributions;
// all contribution ID's of a specific sender
mapping(address => uint256[]) public contributionsBySender;
// the refund BalanceClaim address of a specific refund claim
// maps the (contribution ID => refund claim address)
mapping(uint256 => address) public refundClaimAddress;
// maps the contribution ID to a bool (has the refund been claimed for this
// contribution)
mapping(uint256 => bool) public refundsClaimed;
// the human readable name of the Campaign, for metadata
string public name;
// the contract version number, if any
string constant public version = "0.1.0";
// the contribution method ABI as a string, written in standard solidity
// ABI format, this is generally used so that UI's can understand the campaign
string constant public contributeMethodABI = "contributeMsgValue(uint256[]):(uint256)";
// the payout to beneficiary ABI, written in standard solidity ABI format
string constant public payoutMethodABI = "payoutToBeneficiary()";
// the refund method ABI, written in standard solidity ABI format
string constant public refundMethodABI = "claimRefundOwed(uint256):(address)";
}
/*
This file is part of WeiFund.
*/
/*
An empty campaign enhancer, used to fulfill an enhancer of a WeiFund enhanced
standard campaign.
*/
pragma solidity ^0.4.4;
/// @title Empty Enhancer - used to test enhanced standard campaign contracts
/// @author Nick Dodson <[email protected]>
contract EmptyEnhancer is Enhancer {
/// @dev notate contribution data, and trigger early success if need be
function notate(address _sender, uint256 _value, uint256 _blockNumber, uint256[] _amounts)
public
returns (bool earlySuccess) {
return false;
}
}
/*
A factory contract used for the generation and registration of WeiFund enhanced
standard campaign contracts.
*/
pragma solidity ^0.4.4;
/// @title Enhanced Standard Campaign Factory - used to generate and register standard campaigns
/// @author Nick Dodson <[email protected]>
contract StandardCampaignFactory is PrivateServiceRegistry {
function createStandardCampaign(string _name,
uint256 _expiry,
uint256 _fundingGoal,
uint256 _fundingCap,
address _beneficiary,
address _enhancer) public returns (address campaignAddress) {
// create the new enhanced standard campaign
campaignAddress = address(new StandardCampaign(_name,
_expiry,
_fundingGoal,
_fundingCap,
_beneficiary,
msg.sender,
_enhancer));
// register the campaign address
register(campaignAddress);
}
}
| payout the current balance to the beneficiary, if the crowdfund is in stage success additionally trigger early success, this will force the Success state forcing the success state keeps the contract state machine rigid and ensures other third-party contracts that look to this state that this contract is in state success send funds to the benerifiary | function payoutToBeneficiary() public onlybeneficiary() {
earlySuccess = true;
if (!beneficiary.send(this.balance)) {
throw;
BeneficiaryPayoutClaimed(beneficiary);
}
} else {
}
| 12,875,232 | [
1,
84,
2012,
326,
783,
11013,
358,
326,
27641,
74,
14463,
814,
16,
309,
326,
276,
492,
2180,
1074,
353,
316,
6009,
2216,
2719,
1230,
3080,
11646,
2216,
16,
333,
903,
2944,
326,
11958,
919,
364,
2822,
326,
2216,
919,
20948,
326,
6835,
919,
5228,
436,
28542,
471,
11932,
1308,
12126,
17,
21214,
20092,
716,
2324,
358,
333,
919,
716,
333,
6835,
353,
316,
919,
2216,
1366,
284,
19156,
358,
326,
324,
708,
704,
814,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
293,
2012,
774,
38,
4009,
74,
14463,
814,
1435,
1071,
1338,
70,
4009,
74,
14463,
814,
1435,
288,
203,
565,
11646,
4510,
273,
638,
31,
203,
203,
565,
309,
16051,
70,
4009,
74,
14463,
814,
18,
4661,
12,
2211,
18,
12296,
3719,
288,
203,
1377,
604,
31,
203,
1377,
605,
4009,
74,
14463,
814,
52,
2012,
9762,
329,
12,
70,
4009,
74,
14463,
814,
1769,
203,
565,
289,
203,
565,
289,
469,
288,
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
] |
pragma solidity ^0.4.21;
contract BLInterface {
function setPrimaryAccount(address newMainAddress) public;
function withdraw() public;
}
contract CSInterface {
function goalReached() public;
function goal() public returns (uint);
function hasClosed() public returns(bool);
function weiRaised() public returns (uint);
}
contract StorageInterface {
function getUInt(bytes32 record) public constant returns (uint);
}
contract Interim {
// Define DS, Bubbled and Token Sale addresses
address public owner; // DS wallet
address public bubbled; // bubbled dwallet
BLInterface internal BL; // Blocklord Contract Interface
CSInterface internal CS; // Crowdsale contract interface
StorageInterface internal s; // Eternal Storage Interface
uint public rate; // ETH to GBP rate
function Interim() public {
// Setup owner DS
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyBubbled() {
require(msg.sender == bubbled);
_;
}
modifier onlyMembers() {
require(msg.sender == owner || msg.sender == bubbled);
_;
}
// Setup the interface to the Blocklord contract
function setBLInterface(address newAddress) public onlyOwner {
BL = BLInterface(newAddress);
}
// Setup the interface to the storage contract
function setStorageInterface(address newAddress) public onlyOwner {
s = StorageInterface(newAddress);
}
// Setup the interface to the Blocklord contract
function setCSInterface(address newAddress) public onlyOwner {
CS = CSInterface(newAddress);
}
// Setup the interface to the Bubbled multisig contract
function setBubbled(address newAddress) public onlyMembers {
bubbled = newAddress;
}
// Setup the interface to the DS Personal address
function setDS(address newAddress) public onlyOwner {
owner = newAddress;
}
function setRate(uint _rate) public onlyOwner {
rate = _rate;
}
// we can call this function to check the status of both crowdsale and blocklord
function checkStatus () public returns(uint raisedBL, uint raisedCS, uint total, uint required, bool goalReached){
raisedBL = s.getUInt(keccak256(address(this), "balance"));
raisedCS = CS.weiRaised();
total = raisedBL + raisedCS;
required = CS.goal();
goalReached = total >= required;
}
function completeContract (bool toSplit) public payable {
// require(CS.hasClosed()); // fail if crowdsale has not closed
bool goalReached;
(,,,goalReached) = checkStatus();
if (goalReached) require(toSplit == false);
uint feeDue;
if (toSplit == false) {
feeDue = 20000 / rate * 1000000000000000000; // fee due in Wei
require(msg.value >= feeDue);
}
BL.withdraw(); // withdraw ETH from Blocklord contract to Interim contract
if (goalReached) { // if goal reached
BL.setPrimaryAccount(bubbled); // Transfer Blocklord contract and payment to be maade offline
owner.transfer(feeDue);
bubbled.transfer(this.balance);
} else { // if goal not reached
if (toSplit) { // if Bubbled decides to split
BL.setPrimaryAccount(owner); //set ownership to DS
uint balance = this.balance;
bubbled.transfer(balance / 2);
owner.transfer(balance / 2);
} else {
// Bubbled decides to keep blocklord
BL.setPrimaryAccount(bubbled);
owner.transfer(feeDue);
bubbled.transfer(this.balance);
}
}
}
// receive ether from blocklord contract
function () public payable {
}
} | withdraw ETH from Blocklord contract to Interim contract
| BL.withdraw(); | 10,459,664 | [
1,
1918,
9446,
512,
2455,
628,
3914,
80,
517,
6835,
358,
5294,
381,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1377,
19238,
18,
1918,
9446,
5621,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IERC721, IERC165 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import {Counters} from "@openzeppelin/contracts/utils/Counters.sol";
import { IMarket, Decimal } from "@zoralabs/core/dist/contracts/interfaces/IMarket.sol";
import { IMedia } from "@zoralabs/core/dist/contracts/interfaces/IMedia.sol";
import { IAuctionHouse } from "./interfaces/IAuctionHouse.sol";
interface IWETH {
function deposit() external payable;
function withdraw(uint wad) external;
function transfer(address to, uint256 value) external returns (bool);
}
interface IMediaExtended is IMedia {
function marketContract() external returns(address);
}
/**
* @title An open auction house, enabling collectors and curators to run their own auctions
*/
contract AuctionHouse is IAuctionHouse, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Counters for Counters.Counter;
// The minimum amount of time left in an auction after a new bid is created
uint256 public timeBuffer;
// The minimum percentage difference between the last bid amount and the current bid.
uint8 public minBidIncrementPercentage;
// The address of the zora protocol to use via this contract
address public zora;
// / The address of the WETH contract, so that any ETH transferred can be handled as an ERC-20
address public wethAddress;
// A mapping of all of the auctions currently running.
mapping(uint256 => IAuctionHouse.Auction) public auctions;
bytes4 constant interfaceId = 0x80ac58cd; // 721 interface id
Counters.Counter private _auctionIdTracker;
/**
* @notice Require that the specified auction exists
*/
modifier auctionExists(uint256 auctionId) {
require(_exists(auctionId), "Auction doesn't exist");
_;
}
/*
* Constructor
*/
constructor(address _zora, address _weth) public {
require(
IERC165(_zora).supportsInterface(interfaceId),
"Doesn't support NFT interface"
);
zora = _zora;
wethAddress = _weth;
timeBuffer = 15 * 60; // extend 15 minutes after every bid made in last 15 minutes
minBidIncrementPercentage = 5; // 5%
}
/**
* @notice Create an auction.
* @dev Store the auction details in the auctions mapping and emit an AuctionCreated event.
* If there is no curator, or if the curator is the auction creator, automatically approve the auction.
*/
function createAuction(
uint256 tokenId,
address tokenContract,
uint256 duration,
uint256 reservePrice,
address payable curator,
uint8 curatorFeePercentage,
address auctionCurrency
) public override nonReentrant returns (uint256) {
require(
IERC165(tokenContract).supportsInterface(interfaceId),
"tokenContract does not support ERC721 interface"
);
require(curatorFeePercentage < 100, "curatorFeePercentage must be less than 100");
address tokenOwner = IERC721(tokenContract).ownerOf(tokenId);
require(msg.sender == IERC721(tokenContract).getApproved(tokenId) || msg.sender == tokenOwner, "Caller must be approved or owner for token id");
uint256 auctionId = _auctionIdTracker.current();
auctions[auctionId] = Auction({
tokenId: tokenId,
tokenContract: tokenContract,
approved: false,
amount: 0,
duration: duration,
firstBidTime: 0,
reservePrice: reservePrice,
curatorFeePercentage: curatorFeePercentage,
tokenOwner: tokenOwner,
bidder: address(0),
curator: curator,
auctionCurrency: auctionCurrency
});
IERC721(tokenContract).transferFrom(tokenOwner, address(this), tokenId);
_auctionIdTracker.increment();
emit AuctionCreated(auctionId, tokenId, tokenContract, duration, reservePrice, tokenOwner, curator, curatorFeePercentage, auctionCurrency);
if(auctions[auctionId].curator == address(0) || curator == tokenOwner) {
_approveAuction(auctionId, true);
}
return auctionId;
}
/**
* @notice Approve an auction, opening up the auction for bids.
* @dev Only callable by the curator. Cannot be called if the auction has already started.
*/
function setAuctionApproval(uint256 auctionId, bool approved) external override auctionExists(auctionId) {
require(msg.sender == auctions[auctionId].curator, "Must be auction curator");
require(auctions[auctionId].firstBidTime == 0, "Auction has already started");
_approveAuction(auctionId, approved);
}
function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice) external override auctionExists(auctionId) {
require(msg.sender == auctions[auctionId].curator || msg.sender == auctions[auctionId].tokenOwner, "Must be auction curator or token owner");
require(auctions[auctionId].firstBidTime == 0, "Auction has already started");
auctions[auctionId].reservePrice = reservePrice;
emit AuctionReservePriceUpdated(auctionId, auctions[auctionId].tokenId, auctions[auctionId].tokenContract, reservePrice);
}
/**
* @notice Create a bid on a token, with a given amount.
* @dev If provided a valid bid, transfers the provided amount to this contract.
* If the auction is run in native ETH, the ETH is wrapped so it can be identically to other
* auction currencies in this contract.
*/
function createBid(uint256 auctionId, uint256 amount)
external
override
payable
auctionExists(auctionId)
nonReentrant
{
address payable lastBidder = auctions[auctionId].bidder;
require(auctions[auctionId].approved, "Auction must be approved by curator");
require(
auctions[auctionId].firstBidTime == 0 ||
block.timestamp <
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration),
"Auction expired"
);
require(
amount >= auctions[auctionId].reservePrice,
"Must send at least reservePrice"
);
require(
amount >= auctions[auctionId].amount.add(
auctions[auctionId].amount.mul(minBidIncrementPercentage).div(100)
),
"Must send more than last bid by minBidIncrementPercentage amount"
);
// For Zora Protocol, ensure that the bid is valid for the current bidShare configuration
if(auctions[auctionId].tokenContract == zora) {
require(
IMarket(IMediaExtended(zora).marketContract()).isValidBid(
auctions[auctionId].tokenId,
amount
),
"Bid invalid for share splitting"
);
}
// If this is the first valid bid, we should set the starting time now.
// If it's not, then we should refund the last bidder
if(auctions[auctionId].firstBidTime == 0) {
auctions[auctionId].firstBidTime = block.timestamp;
} else if(lastBidder != address(0)) {
_handleOutgoingBid(lastBidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
}
_handleIncomingBid(amount, auctions[auctionId].auctionCurrency);
auctions[auctionId].amount = amount;
auctions[auctionId].bidder = msg.sender;
bool extended = false;
// at this point we know that the timestamp is less than start + duration (since the auction would be over, otherwise)
// we want to know by how much the timestamp is less than start + duration
// if the difference is less than the timeBuffer, increase the duration by the timeBuffer
if (
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration).sub(
block.timestamp
) < timeBuffer
) {
auctions[auctionId].duration = auctions[auctionId].duration.add(timeBuffer);
extended = true;
}
emit AuctionBid(
auctionId,
auctions[auctionId].tokenId,
auctions[auctionId].tokenContract,
msg.sender,
amount,
lastBidder == address(0), // firstBid boolean
extended
);
}
/**
* @notice End an auction, finalizing the bid on Zora if applicable and paying out the respective parties.
* @dev If for some reason the auction cannot be finalized (invalid token recipient, for example),
* The auction is reset and the NFT is transferred back to the auction creator.
*/
function endAuction(uint256 auctionId) external override auctionExists(auctionId) nonReentrant {
require(
uint256(auctions[auctionId].firstBidTime) != 0,
"Auction hasn't begun"
);
require(
block.timestamp >=
auctions[auctionId].firstBidTime.add(auctions[auctionId].duration),
"Auction hasn't completed"
);
address currency = auctions[auctionId].auctionCurrency == address(0) ? wethAddress : auctions[auctionId].auctionCurrency;
uint256 curatorFee = 0;
uint256 tokenOwnerProfit = auctions[auctionId].amount;
if(auctions[auctionId].tokenContract == zora) {
// If the auction is running on zora, settle it on the protocol
(bool success, uint256 remainingProfit) = _handleZoraAuctionSettlement(auctionId);
tokenOwnerProfit = remainingProfit;
if(success != true) {
_handleOutgoingBid(auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
_cancelAuction(auctionId);
return;
}
} else {
// Otherwise, transfer the token to the winner and pay out the participants below
try IERC721(auctions[auctionId].tokenContract).safeTransferFrom(address(this), auctions[auctionId].bidder, auctions[auctionId].tokenId) {} catch {
_handleOutgoingBid(auctions[auctionId].bidder, auctions[auctionId].amount, auctions[auctionId].auctionCurrency);
_cancelAuction(auctionId);
return;
}
}
if(auctions[auctionId].curator != address(0)) {
curatorFee = tokenOwnerProfit.mul(auctions[auctionId].curatorFeePercentage).div(100);
tokenOwnerProfit = tokenOwnerProfit.sub(curatorFee);
_handleOutgoingBid(auctions[auctionId].curator, curatorFee, auctions[auctionId].auctionCurrency);
}
_handleOutgoingBid(auctions[auctionId].tokenOwner, tokenOwnerProfit, auctions[auctionId].auctionCurrency);
emit AuctionEnded(
auctionId,
auctions[auctionId].tokenId,
auctions[auctionId].tokenContract,
auctions[auctionId].tokenOwner,
auctions[auctionId].curator,
auctions[auctionId].bidder,
tokenOwnerProfit,
curatorFee,
currency
);
delete auctions[auctionId];
}
/**
* @notice Cancel an auction.
* @dev Transfers the NFT back to the auction creator and emits an AuctionCanceled event
*/
function cancelAuction(uint256 auctionId) external override nonReentrant auctionExists(auctionId) {
require(
auctions[auctionId].tokenOwner == msg.sender || auctions[auctionId].curator == msg.sender,
"Can only be called by auction creator or curator"
);
require(
uint256(auctions[auctionId].firstBidTime) == 0,
"Can't cancel an auction once it's begun"
);
_cancelAuction(auctionId);
}
/**
* @dev Given an amount and a currency, transfer the currency to this contract.
* If the currency is ETH (0x0), attempt to wrap the amount as WETH
*/
function _handleIncomingBid(uint256 amount, address currency) internal {
// If this is an ETH bid, ensure they sent enough and convert it to WETH under the hood
if(currency == address(0)) {
require(msg.value == amount, "Sent ETH Value does not match specified bid amount");
IWETH(wethAddress).deposit{value: amount}();
} else {
// We must check the balance that was actually transferred to the auction,
// as some tokens impose a transfer fee and would not actually transfer the
// full amount to the market, resulting in potentally locked funds
IERC20 token = IERC20(currency);
uint256 beforeBalance = token.balanceOf(address(this));
token.safeTransferFrom(msg.sender, address(this), amount);
uint256 afterBalance = token.balanceOf(address(this));
require(beforeBalance.add(amount) == afterBalance, "Token transfer call did not transfer expected amount");
}
}
function _handleOutgoingBid(address to, uint256 amount, address currency) internal {
// If the auction is in ETH, unwrap it from its underlying WETH and try to send it to the recipient.
if(currency == address(0)) {
IWETH(wethAddress).withdraw(amount);
// If the ETH transfer fails (sigh), rewrap the ETH and try send it as WETH.
if(!_safeTransferETH(to, amount)) {
IWETH(wethAddress).deposit{value: amount}();
IERC20(wethAddress).safeTransfer(to, amount);
}
} else {
IERC20(currency).safeTransfer(to, amount);
}
}
function _safeTransferETH(address to, uint256 value) internal returns (bool) {
(bool success, ) = to.call{value: value}(new bytes(0));
return success;
}
function _cancelAuction(uint256 auctionId) internal {
address tokenOwner = auctions[auctionId].tokenOwner;
IERC721(auctions[auctionId].tokenContract).safeTransferFrom(address(this), tokenOwner, auctions[auctionId].tokenId);
emit AuctionCanceled(auctionId, auctions[auctionId].tokenId, auctions[auctionId].tokenContract, tokenOwner);
delete auctions[auctionId];
}
function _approveAuction(uint256 auctionId, bool approved) internal {
auctions[auctionId].approved = approved;
emit AuctionApprovalUpdated(auctionId, auctions[auctionId].tokenId, auctions[auctionId].tokenContract, approved);
}
function _exists(uint256 auctionId) internal returns(bool) {
return auctions[auctionId].tokenOwner != address(0);
}
function _handleZoraAuctionSettlement(uint256 auctionId) internal returns (bool, uint256) {
address currency = auctions[auctionId].auctionCurrency == address(0) ? wethAddress : auctions[auctionId].auctionCurrency;
IMarket.Bid memory bid = IMarket.Bid({
amount: auctions[auctionId].amount,
currency: currency,
bidder: address(this),
recipient: auctions[auctionId].bidder,
sellOnShare: Decimal.D256(0)
});
IERC20(currency).approve(IMediaExtended(zora).marketContract(), bid.amount);
IMedia(zora).setBid(auctions[auctionId].tokenId, bid);
uint256 beforeBalance = IERC20(currency).balanceOf(address(this));
try IMedia(zora).acceptBid(auctions[auctionId].tokenId, bid) {} catch {
// If the underlying NFT transfer here fails, we should cancel the auction and refund the winner
IMediaExtended(zora).removeBid(auctions[auctionId].tokenId);
return (false, 0);
}
uint256 afterBalance = IERC20(currency).balanceOf(address(this));
// We have to calculate the amount to send to the token owner here in case there was a
// sell-on share on the token
return (true, afterBalance.sub(beforeBalance));
}
// TODO: consider reverting if the message sender is not WETH
receive() external payable {}
fallback() external payable {}
}
// 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, 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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../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.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
import {Decimal} from "../Decimal.sol";
/**
* @title Interface for Zora Protocol's Market
*/
interface IMarket {
struct Bid {
// Amount of the currency being bid
uint256 amount;
// Address to the ERC20 token being used to bid
address currency;
// Address of the bidder
address bidder;
// Address of the recipient
address recipient;
// % of the next sale to award the current owner
Decimal.D256 sellOnShare;
}
struct Ask {
// Amount of the currency being asked
uint256 amount;
// Address to the ERC20 token being asked
address currency;
}
struct BidShares {
// % of sale value that goes to the _previous_ owner of the nft
Decimal.D256 prevOwner;
// % of sale value that goes to the original creator of the nft
Decimal.D256 creator;
// % of sale value that goes to the seller (current owner) of the nft
Decimal.D256 owner;
}
event BidCreated(uint256 indexed tokenId, Bid bid);
event BidRemoved(uint256 indexed tokenId, Bid bid);
event BidFinalized(uint256 indexed tokenId, Bid bid);
event AskCreated(uint256 indexed tokenId, Ask ask);
event AskRemoved(uint256 indexed tokenId, Ask ask);
event BidShareUpdated(uint256 indexed tokenId, BidShares bidShares);
function bidForTokenBidder(uint256 tokenId, address bidder)
external
view
returns (Bid memory);
function currentAskForToken(uint256 tokenId)
external
view
returns (Ask memory);
function bidSharesForToken(uint256 tokenId)
external
view
returns (BidShares memory);
function isValidBid(uint256 tokenId, uint256 bidAmount)
external
view
returns (bool);
function isValidBidShares(BidShares calldata bidShares)
external
pure
returns (bool);
function splitShare(Decimal.D256 calldata sharePercentage, uint256 amount)
external
pure
returns (uint256);
function configure(address mediaContractAddress) external;
function setBidShares(uint256 tokenId, BidShares calldata bidShares)
external;
function setAsk(uint256 tokenId, Ask calldata ask) external;
function removeAsk(uint256 tokenId) external;
function setBid(
uint256 tokenId,
Bid calldata bid,
address spender
) external;
function removeBid(uint256 tokenId, address bidder) external;
function acceptBid(uint256 tokenId, Bid calldata expectedBid) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
import {IMarket} from "./IMarket.sol";
/**
* @title Interface for Zora Protocol's Media
*/
interface IMedia {
struct EIP712Signature {
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
struct MediaData {
// A valid URI of the content represented by this token
string tokenURI;
// A valid URI of the metadata associated with this token
string metadataURI;
// A SHA256 hash of the content pointed to by tokenURI
bytes32 contentHash;
// A SHA256 hash of the content pointed to by metadataURI
bytes32 metadataHash;
}
event TokenURIUpdated(uint256 indexed _tokenId, address owner, string _uri);
event TokenMetadataURIUpdated(
uint256 indexed _tokenId,
address owner,
string _uri
);
/**
* @notice Return the metadata URI for a piece of media given the token URI
*/
function tokenMetadataURI(uint256 tokenId)
external
view
returns (string memory);
/**
* @notice Mint new media for msg.sender.
*/
function mint(MediaData calldata data, IMarket.BidShares calldata bidShares)
external;
/**
* @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature.
*/
function mintWithSig(
address creator,
MediaData calldata data,
IMarket.BidShares calldata bidShares,
EIP712Signature calldata sig
) external;
/**
* @notice Transfer the token with the given ID to a given address.
* Save the previous owner before the transfer, in case there is a sell-on fee.
* @dev This can only be called by the auction contract specified at deployment
*/
function auctionTransfer(uint256 tokenId, address recipient) external;
/**
* @notice Set the ask on a piece of media
*/
function setAsk(uint256 tokenId, IMarket.Ask calldata ask) external;
/**
* @notice Remove the ask on a piece of media
*/
function removeAsk(uint256 tokenId) external;
/**
* @notice Set the bid on a piece of media
*/
function setBid(uint256 tokenId, IMarket.Bid calldata bid) external;
/**
* @notice Remove the bid on a piece of media
*/
function removeBid(uint256 tokenId) external;
function acceptBid(uint256 tokenId, IMarket.Bid calldata bid) external;
/**
* @notice Revoke approval for a piece of media
*/
function revokeApproval(uint256 tokenId) external;
/**
* @notice Update the token URI
*/
function updateTokenURI(uint256 tokenId, string calldata tokenURI) external;
/**
* @notice Update the token metadata uri
*/
function updateTokenMetadataURI(
uint256 tokenId,
string calldata metadataURI
) external;
/**
* @notice EIP-712 permit method. Sets an approved spender given a valid signature.
*/
function permit(
address spender,
uint256 tokenId,
EIP712Signature calldata sig
) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
/**
* @title Interface for Auction Houses
*/
interface IAuctionHouse {
struct Auction {
// ID for the ERC721 token
uint256 tokenId;
// Address for the ERC721 contract
address tokenContract;
// Whether or not the auction curator has approved the auction to start
bool approved;
// The current highest bid amount
uint256 amount;
// The length of time to run the auction for, after the first bid was made
uint256 duration;
// The time of the first bid
uint256 firstBidTime;
// The minimum price of the first bid
uint256 reservePrice;
// The sale percentage to send to the curator
uint8 curatorFeePercentage;
// The address that should receive the funds once the NFT is sold.
address tokenOwner;
// The address of the current highest bid
address payable bidder;
// The address of the auction's curator.
// The curator can reject or approve an auction
address payable curator;
// The address of the ERC-20 currency to run the auction with.
// If set to 0x0, the auction will be run in ETH
address auctionCurrency;
}
event AuctionCreated(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
uint256 duration,
uint256 reservePrice,
address tokenOwner,
address curator,
uint8 curatorFeePercentage,
address auctionCurrency
);
event AuctionApprovalUpdated(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
bool approved
);
event AuctionReservePriceUpdated(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
uint256 reservePrice
);
event AuctionBid(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address sender,
uint256 value,
bool firstBid,
bool extended
);
event AuctionEnded(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address tokenOwner,
address curator,
address winner,
uint256 amount,
uint256 curatorFee,
address auctionCurrency
);
event AuctionCanceled(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address tokenOwner
);
function createAuction(
uint256 tokenId,
address tokenContract,
uint256 duration,
uint256 reservePrice,
address payable curator,
uint8 curatorFeePercentages,
address auctionCurrency
) external returns (uint256);
function setAuctionApproval(uint256 auctionId, bool approved) external;
function setAuctionReservePrice(uint256 auctionId, uint256 reservePrice) external;
function createBid(uint256 auctionId, uint256 amount) external payable;
function endAuction(uint256 auctionId) external;
function cancelAuction(uint256 auctionId) external;
}
// 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.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);
}
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);
}
}
}
}
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
/**
* NOTE: This file is a clone of the dydx protocol's Decimal.sol contract. It was forked from https://github.com/dydxprotocol/solo
* at commit 2d8454e02702fe5bc455b848556660629c3cad36
*
* It has not been modified other than to use a newer solidity in the pragma to match the rest of the contract suite of this project
*/
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
import {Math} from "./Math.sol";
/**
* @title Decimal
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
uint256 constant BASE_POW = 18;
uint256 constant BASE = 10**BASE_POW;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Functions ============
function one() internal pure returns (D256 memory) {
return D256({value: BASE});
}
function onePlus(D256 memory d) internal pure returns (D256 memory) {
return D256({value: d.value.add(BASE)});
}
function mul(uint256 target, D256 memory d)
internal
pure
returns (uint256)
{
return Math.getPartial(target, d.value, BASE);
}
function div(uint256 target, D256 memory d)
internal
pure
returns (uint256)
{
return Math.getPartial(target, BASE, d.value);
}
}
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
import {SafeMath} from "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @title Math
*
* Library for non-standard Math functions
* NOTE: This file is a clone of the dydx protocol's Decimal.sol contract.
* It was forked from https://github.com/dydxprotocol/solo at commit
* 2d8454e02702fe5bc455b848556660629c3cad36. It has not been modified other than to use a
* newer solidity in the pragma to match the rest of the contract suite of this project.
*/
library Math {
using SafeMath for uint256;
// ============ Library Functions ============
/*
* Return target * (numerator / denominator).
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
) internal pure returns (uint256) {
return target.mul(numerator).div(denominator);
}
/*
* Return target * (numerator / denominator), but rounded up.
*/
function getPartialRoundUp(
uint256 target,
uint256 numerator,
uint256 denominator
) internal pure returns (uint256) {
if (target == 0 || numerator == 0) {
// SafeMath will check for zero denominator
return SafeMath.div(0, denominator);
}
return target.mul(numerator).sub(1).div(denominator).add(1);
}
function to128(uint256 number) internal pure returns (uint128) {
uint128 result = uint128(number);
require(result == number, "Math: Unsafe cast to uint128");
return result;
}
function to96(uint256 number) internal pure returns (uint96) {
uint96 result = uint96(number);
require(result == number, "Math: Unsafe cast to uint96");
return result;
}
function to32(uint256 number) internal pure returns (uint32) {
uint32 result = uint32(number);
require(result == number, "Math: Unsafe cast to uint32");
return result;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
}
| * @notice Return the metadata URI for a piece of media given the token URI/* @notice Mint new media for msg.sender./* @notice EIP-712 mintWithSig method. Mints new media for a creator given a valid signature./* @notice Transfer the token with the given ID to a given address. Save the previous owner before the transfer, in case there is a sell-on fee. @dev This can only be called by the auction contract specified at deployment/* @notice Set the ask on a piece of media/* @notice Remove the ask on a piece of media/* @notice Set the bid on a piece of media/* @notice Remove the bid on a piece of media/* @notice Revoke approval for a piece of media/* @notice Update the token URI/* @notice Update the token metadata uri/* @notice EIP-712 permit method. Sets an approved spender given a valid signature./ SPDX-License-Identifier: GPL-3.0* @title Interface for Auction Houses/ | interface IAuctionHouse {
function tokenMetadataURI(uint256 tokenId)
external
view
returns (string memory);
function mint(MediaData calldata data, IMarket.BidShares calldata bidShares)
external;
function mintWithSig(
address creator,
MediaData calldata data,
IMarket.BidShares calldata bidShares,
EIP712Signature calldata sig
) external;
function auctionTransfer(uint256 tokenId, address recipient) external;
function setAsk(uint256 tokenId, IMarket.Ask calldata ask) external;
function removeAsk(uint256 tokenId) external;
function setBid(uint256 tokenId, IMarket.Bid calldata bid) external;
function removeBid(uint256 tokenId) external;
function acceptBid(uint256 tokenId, IMarket.Bid calldata bid) external;
function revokeApproval(uint256 tokenId) external;
function updateTokenURI(uint256 tokenId, string calldata tokenURI) external;
function updateTokenMetadataURI(
uint256 tokenId,
string calldata metadataURI
) external;
function permit(
address spender,
uint256 tokenId,
EIP712Signature calldata sig
) external;
}
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
struct Auction {
uint256 tokenId;
address tokenContract;
bool approved;
uint256 amount;
uint256 duration;
uint256 firstBidTime;
uint256 reservePrice;
uint8 curatorFeePercentage;
address tokenOwner;
address payable bidder;
address payable curator;
address auctionCurrency;
}
event AuctionCreated(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
uint256 duration,
uint256 reservePrice,
address tokenOwner,
address curator,
uint8 curatorFeePercentage,
address auctionCurrency
);
event AuctionApprovalUpdated(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
bool approved
);
event AuctionReservePriceUpdated(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
uint256 reservePrice
);
event AuctionBid(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address sender,
uint256 value,
bool firstBid,
bool extended
);
event AuctionEnded(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address tokenOwner,
address curator,
address winner,
uint256 amount,
uint256 curatorFee,
address auctionCurrency
);
event AuctionCanceled(
uint256 indexed auctionId,
uint256 indexed tokenId,
address indexed tokenContract,
address tokenOwner
);
}
| 13,747,464 | [
1,
990,
326,
1982,
3699,
364,
279,
11151,
434,
3539,
864,
326,
1147,
3699,
19,
225,
490,
474,
394,
3539,
364,
1234,
18,
15330,
18,
19,
225,
512,
2579,
17,
27,
2138,
312,
474,
1190,
8267,
707,
18,
490,
28142,
394,
3539,
364,
279,
11784,
864,
279,
923,
3372,
18,
19,
225,
12279,
326,
1147,
598,
326,
864,
1599,
358,
279,
864,
1758,
18,
7074,
326,
2416,
3410,
1865,
326,
7412,
16,
316,
648,
1915,
353,
279,
357,
80,
17,
265,
14036,
18,
225,
1220,
848,
1338,
506,
2566,
635,
326,
279,
4062,
6835,
1269,
622,
6314,
19,
225,
1000,
326,
6827,
603,
279,
11151,
434,
3539,
19,
225,
3581,
326,
6827,
603,
279,
11151,
434,
3539,
19,
225,
1000,
326,
9949,
603,
279,
11151,
434,
3539,
19,
225,
3581,
326,
9949,
603,
279,
11151,
434,
3539,
19,
225,
23863,
23556,
364,
279,
11151,
434,
3539,
19,
225,
2315,
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,
5831,
467,
37,
4062,
44,
3793,
288,
203,
565,
445,
1147,
2277,
3098,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
1080,
3778,
1769,
203,
203,
565,
445,
312,
474,
12,
5419,
751,
745,
892,
501,
16,
467,
3882,
278,
18,
17763,
24051,
745,
892,
9949,
24051,
13,
203,
3639,
3903,
31,
203,
203,
565,
445,
312,
474,
1190,
8267,
12,
203,
3639,
1758,
11784,
16,
203,
3639,
6128,
751,
745,
892,
501,
16,
203,
3639,
467,
3882,
278,
18,
17763,
24051,
745,
892,
9949,
24051,
16,
203,
3639,
512,
2579,
27,
2138,
5374,
745,
892,
3553,
203,
565,
262,
3903,
31,
203,
203,
565,
445,
279,
4062,
5912,
12,
11890,
5034,
1147,
548,
16,
1758,
8027,
13,
3903,
31,
203,
203,
565,
445,
444,
23663,
12,
11890,
5034,
1147,
548,
16,
467,
3882,
278,
18,
23663,
745,
892,
6827,
13,
3903,
31,
203,
203,
565,
445,
1206,
23663,
12,
11890,
5034,
1147,
548,
13,
3903,
31,
203,
203,
565,
445,
15268,
350,
12,
11890,
5034,
1147,
548,
16,
467,
3882,
278,
18,
17763,
745,
892,
9949,
13,
3903,
31,
203,
203,
565,
445,
1206,
17763,
12,
11890,
5034,
1147,
548,
13,
3903,
31,
203,
203,
565,
445,
2791,
17763,
12,
11890,
5034,
1147,
548,
16,
467,
3882,
278,
18,
17763,
745,
892,
9949,
13,
3903,
31,
203,
203,
565,
445,
18007,
23461,
12,
11890,
5034,
1147,
548,
13,
3903,
31,
203,
203,
565,
445,
1089,
1345,
3098,
12,
11890,
5034,
1147,
548,
16,
533,
745,
2
] |
//Address: 0xacdbfec3d91870260a704f96cd7bd8c0a6c5aa1c
//Contract name: DollarAuction
//Balance: 0 Ether
//Verification Date: 2/8/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.17;
contract DollarAuction {
struct Bid {
address sender;
uint amount;
uint time;
}
Bid[] bids;
uint bidsPtr = 0;
uint interval = 60;
uint step = 1;
uint minBid = 10000000000000000;
uint total = 0;
event LogBidMade(address accountAddress, uint amount, uint time);
event LogBidFailed(address accountAddress, uint amount, uint time);
event LogBidFinal(address accountAddress, uint amount, uint time, uint profit);
event LogBidReturned(address accountAddress, uint amount, uint time);
event LogPayoutFailed(address accountAddress, uint amount, uint time);
event BidSaved(Bid bid);
function DollarAuction() {
bids.length = 100000;
}
function bid() public payable returns (bool success) {
//if (bidsPtr == bids.length -1) bids.length = bids.length + 100;
uint amount = msg.value;
uint lastBidAmount = getLastBidAmount();
address sender = msg.sender;
uint time = now;
require(amount > minBid);
require(amount > (lastBidAmount + step));
bids[bidsPtr] = Bid({time: now, sender: sender, amount: amount});
bidsPtr = bidsPtr + 1;
total = total + amount;
LogBidMade(sender, amount, time);
if (isBidFinal()) {
uint payout = total;
total = 0;
if (!sender.send(payout)) {
total = payout;
LogPayoutFailed(sender, amount, time);
return false;
}
bidsPtr = 0;
LogBidFinal(sender, amount, time, total);
}
return true;
}
function getLastBidAmount() constant public returns (uint lastBidAmount) {
if (bidsPtr == 0) return 0;
else return bids[bidsPtr-1].amount;
}
function getTotalBidded() constant public returns (uint totalBidded) {
return total;
}
function isBidFinal() constant public returns (bool isFinal) {
if (bidsPtr <= 1) return false;
return ((bids[bidsPtr-1].time - bids[bidsPtr-2].time) > interval);
}
function getTimeOfLastBid() constant public returns (uint time) {
if (bidsPtr == 0) return now;
return bids[bidsPtr-1].time;
}
function getMinBid() constant public returns (uint minimumBid) {
return minBid;
}
function () public payable {
revert();
}
}
| if (bidsPtr == bids.length -1) bids.length = bids.length + 100; | function bid() public payable returns (bool success) {
uint amount = msg.value;
uint lastBidAmount = getLastBidAmount();
address sender = msg.sender;
uint time = now;
require(amount > minBid);
require(amount > (lastBidAmount + step));
bidsPtr = bidsPtr + 1;
total = total + amount;
LogBidMade(sender, amount, time);
if (isBidFinal()) {
uint payout = total;
total = 0;
if (!sender.send(payout)) {
total = payout;
LogPayoutFailed(sender, amount, time);
return false;
}
bidsPtr = 0;
LogBidFinal(sender, amount, time, total);
}
return true;
}
| 1,769,418 | [
1,
430,
261,
70,
2232,
5263,
422,
30534,
18,
2469,
300,
21,
13,
30534,
18,
2469,
273,
30534,
18,
2469,
397,
2130,
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
] | [
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,
9949,
1435,
1071,
8843,
429,
1135,
261,
6430,
2216,
13,
288,
203,
1377,
2254,
3844,
273,
1234,
18,
1132,
31,
203,
1377,
2254,
1142,
17763,
6275,
273,
7595,
17763,
6275,
5621,
203,
1377,
1758,
5793,
273,
1234,
18,
15330,
31,
203,
1377,
2254,
813,
273,
2037,
31,
203,
1377,
2583,
12,
8949,
405,
1131,
17763,
1769,
203,
1377,
2583,
12,
8949,
405,
261,
2722,
17763,
6275,
397,
2235,
10019,
203,
1377,
30534,
5263,
273,
30534,
5263,
397,
404,
31,
203,
1377,
2078,
273,
2078,
397,
3844,
31,
203,
1377,
1827,
17763,
49,
2486,
12,
15330,
16,
3844,
16,
813,
1769,
203,
1377,
309,
261,
291,
17763,
7951,
10756,
288,
203,
3639,
2254,
293,
2012,
273,
2078,
31,
203,
3639,
2078,
273,
374,
31,
203,
3639,
309,
16051,
15330,
18,
4661,
12,
84,
2012,
3719,
288,
203,
1850,
2078,
273,
293,
2012,
31,
203,
1850,
1827,
52,
2012,
2925,
12,
15330,
16,
3844,
16,
813,
1769,
203,
1850,
327,
629,
31,
203,
3639,
289,
203,
3639,
30534,
5263,
273,
374,
31,
203,
3639,
1827,
17763,
7951,
12,
15330,
16,
3844,
16,
813,
16,
2078,
1769,
203,
1377,
289,
203,
1377,
327,
638,
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
] |
pragma solidity ^0.5.10;
/** @title A contract for generating unique identifiers
*
* @notice A contract that provides an identifier generation scheme,
* guaranteeing uniqueness across all contracts that inherit from it,
* as well as the unpredictability of future identifiers.
*
* @dev This contract is intended to be inherited by any contract that
* implements the callback software pattern for cooperative custodianship.
*
*/
contract LockRequestable {
// MEMBERS
/// @notice the count of all invocations of `generateLockId`.
uint256 public lockRequestCount;
// CONSTRUCTOR
constructor() public {
lockRequestCount = 0;
}
// FUNCTIONS
/** @notice Returns a fresh unique identifier.
*
* @dev the generation scheme uses three components.
* First, the blockhash of the previous block.
* Second, the deployed address.
* Third, the next value of the counter.
* This ensures that identifiers are unique across all contracts
* following this scheme, and that future identifiers are
* unpredictable.
*
* @return a 32-byte unique identifier.
*/
function generateLockId() internal returns (bytes32 lockId) {
return keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), ++lockRequestCount));
}
}
contract ERC20Interface {
// METHODS
// NOTE:
// public getter functions are not currently recognised as an
// implementation of the matching abstract function by the compiler.
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#name
// function name() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#symbol
// function symbol() public view returns (string);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
// function decimals() public view returns (uint8);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#totalsupply
function totalSupply() public view returns (uint256);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#balanceof
function balanceOf(address _owner) public view returns (uint256 balance);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer
function transfer(address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transferfrom
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
function approve(address _spender, uint256 _value) public returns (bool success);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#allowance
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
// EVENTS
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#transfer-1
event Transfer(address indexed _from, address indexed _to, uint256 _value);
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approval
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/** @title A dual control contract.
*
* @notice A general-purpose contract that implements dual control over
* co-operating contracts through a callback mechanism.
*
* @dev This contract implements dual control through a 2-of-N
* threshold multi-signature scheme. The contract recognizes a set of N signers,
* and will unlock requests with signatures from any distinct pair of them.
* This contract signals the unlocking through a co-operative callback
* scheme.
* This contract also provides time lock and revocation features.
* Requests made by a 'primary' account have a default time lock applied.
* All other requests must pay a 1 ETH stake and have an extended time lock
* applied.
* A request that is completed will prevent all previous pending requests
* that share the same callback from being completed: this is the
* revocation feature.
*
*/
contract Custodian {
// TYPES
/** @dev The `Request` struct stores a pending unlocking.
* `callbackAddress` and `callbackSelector` are the data required to
* make a callback. The custodian completes the process by
* calling `callbackAddress.call(callbackSelector, lockId)`, which
* signals to the contract co-operating with the Custodian that
* the 2-of-N signatures have been provided and verified.
*/
struct Request {
bytes32 lockId;
bytes4 callbackSelector; // bytes4 and address can be packed into 1 word
address callbackAddress;
uint256 idx;
uint256 timestamp;
bool extended;
}
// EVENTS
/// @dev Emitted by successful `requestUnlock` calls.
event Requested(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
uint256 _nonce,
address _whitelistedAddress,
bytes32 _requestMsgHash,
uint256 _timeLockExpiry
);
/// @dev Emitted by `completeUnlock` calls on requests in the time-locked state.
event TimeLocked(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
/// @dev Emitted by successful `completeUnlock` calls.
event Completed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by `completeUnlock` calls where the callback failed.
event Failed(
bytes32 _lockId,
bytes32 _requestMsgHash,
address _signer1,
address _signer2
);
/// @dev Emitted by successful `extendRequestTimeLock` calls.
event TimeLockExtended(
uint256 _timeLockExpiry,
bytes32 _requestMsgHash
);
// MEMBERS
/** @dev The count of all requests.
* This value is used as a nonce, incorporated into the request hash.
*/
uint256 public requestCount;
/// @dev The set of signers: signatures from two signers unlock a pending request.
mapping (address => bool) public signerSet;
/// @dev The map of request hashes to pending requests.
mapping (bytes32 => Request) public requestMap;
/// @dev The map of callback addresses to callback selectors to request indexes.
mapping (address => mapping (bytes4 => uint256)) public lastCompletedIdxs;
/** @dev The default period (in seconds) to time-lock requests.
* All requests will be subject to this default time lock, and the duration
* is fixed at contract creation.
*/
uint256 public defaultTimeLock;
/** @dev The extended period (in seconds) to time-lock requests.
* Requests not from the primary account are subject to this time lock.
* The primary account may also elect to extend the time lock on requests
* that originally received the default.
*/
uint256 public extendedTimeLock;
/// @dev The primary account is the privileged account for making requests.
address public primary;
// CONSTRUCTOR
constructor(
address[] memory _signers,
uint256 _defaultTimeLock,
uint256 _extendedTimeLock,
address _primary
)
public
{
// check for at least two `_signers`
require(_signers.length >= 2, "at least two `_signers`");
// validate time lock params
require(_defaultTimeLock <= _extendedTimeLock, "valid timelock params");
defaultTimeLock = _defaultTimeLock;
extendedTimeLock = _extendedTimeLock;
primary = _primary;
// explicitly initialize `requestCount` to zero
requestCount = 0;
// turn the array into a set
for (uint i = 0; i < _signers.length; i++) {
// no zero addresses or duplicates
require(_signers[i] != address(0) && !signerSet[_signers[i]], "no zero addresses or duplicates");
signerSet[_signers[i]] = true;
}
}
// MODIFIERS
modifier onlyPrimary {
require(msg.sender == primary, "only primary");
_;
}
modifier onlySigner {
require(signerSet[msg.sender], "only signer");
_;
}
// METHODS
/** @notice Requests an unlocking with a lock identifier and a callback.
*
* @dev If called by an account other than the primary a 1 ETH stake
* must be paid. When the request is unlocked stake will be transferred to the message sender.
* This is an anti-spam measure. As well as the callback
* and the lock identifier parameters a 'whitelisted address' is required
* for compatibility with existing signature schemes.
*
* @param _lockId The identifier of a pending request in a co-operating contract.
* @param _callbackAddress The address of a co-operating contract.
* @param _callbackSelector The function selector of a function within
* the co-operating contract at address `_callbackAddress`.
* @param _whitelistedAddress An address whitelisted in existing
* offline control protocols.
*
* @return requestMsgHash The hash of a request message to be signed.
*/
function requestUnlock(
bytes32 _lockId,
address _callbackAddress,
bytes4 _callbackSelector,
address _whitelistedAddress
)
public
payable
returns (bytes32 requestMsgHash)
{
require(msg.sender == primary || msg.value >= 1 ether, "sender is primary or stake is paid");
// disallow using a zero value for the callback address
require(_callbackAddress != address(0), "no zero value for callback address");
uint256 requestIdx = ++requestCount;
// compute a nonce value
// - the blockhash prevents prediction of future nonces
// - the address of this contract prevents conflicts with co-operating contracts using this scheme
// - the counter prevents conflicts arising from multiple txs within the same block
uint256 nonce = uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), address(this), requestIdx)));
requestMsgHash = keccak256(
abi.encodePacked(
nonce,
_whitelistedAddress,
uint256(0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
)
);
requestMap[requestMsgHash] = Request({
lockId: _lockId,
callbackSelector: _callbackSelector,
callbackAddress: _callbackAddress,
idx: requestIdx,
timestamp: block.timestamp,
extended: false
});
// compute the expiry time
uint256 timeLockExpiry = block.timestamp;
if (msg.sender == primary) {
timeLockExpiry += defaultTimeLock;
} else {
timeLockExpiry += extendedTimeLock;
// any sender that is not the creator will get the extended time lock
requestMap[requestMsgHash].extended = true;
}
emit Requested(_lockId, _callbackAddress, _callbackSelector, nonce, _whitelistedAddress, requestMsgHash, timeLockExpiry);
}
/** @notice Completes a pending unlocking with two signatures.
*
* @dev Given a request message hash as two signatures of it from
* two distinct signers in the signer set, this function completes the
* unlocking of the pending request by executing the callback.
*
* @param _requestMsgHash The request message hash of a pending request.
* @param _recoveryByte1 The public key recovery byte (27 or 28)
* @param _ecdsaR1 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS1 The S component of an ECDSA signature (R, S) pair
* @param _recoveryByte2 The public key recovery byte (27 or 28)
* @param _ecdsaR2 The R component of an ECDSA signature (R, S) pair
* @param _ecdsaS2 The S component of an ECDSA signature (R, S) pair
*
* @return success True if the callback successfully executed.
*/
function completeUnlock(
bytes32 _requestMsgHash,
uint8 _recoveryByte1, bytes32 _ecdsaR1, bytes32 _ecdsaS1,
uint8 _recoveryByte2, bytes32 _ecdsaR2, bytes32 _ecdsaS2
)
public
onlySigner
returns (bool success)
{
Request storage request = requestMap[_requestMsgHash];
// copy storage to locals before `delete`
bytes32 lockId = request.lockId;
address callbackAddress = request.callbackAddress;
bytes4 callbackSelector = request.callbackSelector;
// failing case of the lookup if the callback address is zero
require(callbackAddress != address(0), "no zero value for callback address");
// reject confirms of earlier withdrawals buried under later confirmed withdrawals
require(request.idx > lastCompletedIdxs[callbackAddress][callbackSelector],
"reject confirms of earlier withdrawals buried under later confirmed withdrawals");
address signer1 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte1,
_ecdsaR1,
_ecdsaS1
);
require(signerSet[signer1], "signer is set");
address signer2 = ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _requestMsgHash)),
_recoveryByte2,
_ecdsaR2,
_ecdsaS2
);
require(signerSet[signer2], "signer is set");
require(signer1 != signer2, "signers are different");
if (request.extended && ((block.timestamp - request.timestamp) < extendedTimeLock)) {
emit TimeLocked(request.timestamp + extendedTimeLock, _requestMsgHash);
return false;
} else if ((block.timestamp - request.timestamp) < defaultTimeLock) {
emit TimeLocked(request.timestamp + defaultTimeLock, _requestMsgHash);
return false;
} else {
if (address(this).balance > 0) {
// reward sender with anti-spam payments
msg.sender.transfer(address(this).balance);
}
// raise the waterline for the last completed unlocking
lastCompletedIdxs[callbackAddress][callbackSelector] = request.idx;
// and delete the request
delete requestMap[_requestMsgHash];
// invoke callback
(success,) = (false, bytes(msg.data));
callbackAddress.call(abi.encodeWithSelector(callbackSelector, lockId)); //inject UNHANDLED EXCEPTION
if (success) {
emit Completed(lockId, _requestMsgHash, signer1, signer2);
} else {
emit Failed(lockId, _requestMsgHash, signer1, signer2);
}
}
}
/** @notice Reclaim the storage of a pending request that is uncompletable.
*
* @dev If a pending request shares the callback (address and selector) of
* a later request has been completed, then the request can no longer
* be completed. This function will reclaim the contract storage of the
* pending request.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function deleteUncompletableRequest(bytes32 _requestMsgHash) public {
Request storage request = requestMap[_requestMsgHash];
uint256 idx = request.idx;
require(0 < idx && idx < lastCompletedIdxs[request.callbackAddress][request.callbackSelector],
"there must be a completed latter request with same callback");
delete requestMap[_requestMsgHash];
}
/** @notice Extend the time lock of a pending request.
*
* @dev Requests made by the primary account receive the default time lock.
* This function allows the primary account to apply the extended time lock
* to one its own requests.
*
* @param _requestMsgHash The request message hash of a pending request.
*/
function extendRequestTimeLock(bytes32 _requestMsgHash) public onlyPrimary {
Request storage request = requestMap[_requestMsgHash];
// reject 1null1 results from the map lookup
// this can only be the case if an unknown `_requestMsgHash` is received
require(request.callbackAddress != address(0), "reject 1null1 results from the map lookup");
// `extendRequestTimeLock` must be idempotent
require(request.extended != true, "`extendRequestTimeLock` must be idempotent");
// set the `extended` flag; note that this is never unset
request.extended = true;
emit TimeLockExtended(request.timestamp + extendedTimeLock, _requestMsgHash);
}
}
/** @title A contract to inherit upgradeable custodianship.
*
* @notice A contract that provides re-usable code for upgradeable
* custodianship. That custodian may be an account or another contract.
*
* @dev This contract is intended to be inherited by any contract
* requiring a custodian to control some aspect of its functionality.
* This contract provides the mechanism for that custodianship to be
* passed from one custodian to the next.
*
*/
contract CustodianUpgradeable is LockRequestable {
// TYPES
/// @dev The struct type for pending custodian changes.
struct CustodianChangeRequest {
address proposedNew;
}
// MEMBERS
/// @dev The address of the account or contract that acts as the custodian.
address public custodian;
/// @dev The map of lock ids to pending custodian changes.
mapping (bytes32 => CustodianChangeRequest) public custodianChangeReqs;
// CONSTRUCTOR
constructor(
address _custodian
)
LockRequestable()
public
{
custodian = _custodian;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == custodian, "only custodian");
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the custodian associated with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedCustodian The address of the new custodian.
* @return lockId A unique identifier for this request.
*/
function requestCustodianChange(address _proposedCustodian) public returns (bytes32 lockId) {
require(_proposedCustodian != address(0), "no null value for `_proposedCustodian`");
lockId = generateLockId();
custodianChangeReqs[lockId] = CustodianChangeRequest({
proposedNew: _proposedCustodian
});
emit CustodianChangeRequested(lockId, msg.sender, _proposedCustodian);
}
/** @notice Confirms a pending change of the custodian associated with this contract.
*
* @dev When called by the current custodian with a lock id associated with a
* pending custodian change, the `address custodian` member will be updated with the
* requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmCustodianChange(bytes32 _lockId) public onlyCustodian {
custodian = getCustodianChangeReq(_lockId);
delete custodianChangeReqs[_lockId];
emit CustodianChangeConfirmed(_lockId, custodian);
}
// PRIVATE FUNCTIONS
function getCustodianChangeReq(bytes32 _lockId) private view returns (address _proposedNew) {
CustodianChangeRequest storage changeRequest = custodianChangeReqs[_lockId];
// reject 1null1 results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0), "reject 1null1 results from the map lookup");
return changeRequest.proposedNew;
}
//EVENTS
/// @dev Emitted by successful `requestCustodianChange` calls.
event CustodianChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedCustodian
);
/// @dev Emitted by successful `confirmCustodianChange` calls.
event CustodianChangeConfirmed(bytes32 _lockId, address _newCustodian);
}
/** @title A contract to inherit upgradeable token implementations.
*
* @notice A contract that provides re-usable code for upgradeable
* token implementations. It itself inherits from `CustodianUpgradable`
* as the upgrade process is controlled by the custodian.
*
* @dev This contract is intended to be inherited by any contract
* requiring a reference to the active token implementation, either
* to delegate calls to it, or authorize calls from it. This contract
* provides the mechanism for that implementation to be replaced,
* which constitutes an implementation upgrade.
*
*/
contract ERC20ImplUpgradeable is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending implementation changes.
struct ImplChangeRequest {
address proposedNew;
}
// MEMBERS
// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The map of lock ids to pending implementation changes.
mapping (bytes32 => ImplChangeRequest) public implChangeReqs;
// CONSTRUCTOR
constructor(address _custodian) CustodianUpgradeable(_custodian) public {
erc20Impl = ERC20Impl(0x0);
}
// MODIFIERS
modifier onlyImpl {
require(msg.sender == address(erc20Impl), "only ERC20Impl");
_;
}
// PUBLIC FUNCTIONS
// (UPGRADE)
/** @notice Requests a change of the active implementation associated
* with this contract.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _proposedImpl The address of the new active implementation.
* @return lockId A unique identifier for this request.
*/
function requestImplChange(address _proposedImpl) public returns (bytes32 lockId) {
require(_proposedImpl != address(0), "no null value for `_proposedImpl`");
lockId = generateLockId();
implChangeReqs[lockId] = ImplChangeRequest({
proposedNew: _proposedImpl
});
emit ImplChangeRequested(lockId, msg.sender, _proposedImpl);
}
/** @notice Confirms a pending change of the active implementation
* associated with this contract.
*
* @dev When called by the custodian with a lock id associated with a
* pending change, the `ERC20Impl erc20Impl` member will be updated
* with the requested address.
*
* @param _lockId The identifier of a pending change request.
*/
function confirmImplChange(bytes32 _lockId) public onlyCustodian {
erc20Impl = getImplChangeReq(_lockId);
delete implChangeReqs[_lockId];
emit ImplChangeConfirmed(_lockId, address(erc20Impl));
}
// PRIVATE FUNCTIONS
function getImplChangeReq(bytes32 _lockId) private view returns (ERC20Impl _proposedNew) {
ImplChangeRequest storage changeRequest = implChangeReqs[_lockId];
// reject 1null1 results from the map lookup
// this can only be the case if an unknown `_lockId` is received
require(changeRequest.proposedNew != address(0), "reject 1null1 results from the map lookup");
return ERC20Impl(changeRequest.proposedNew);
}
//EVENTS
/// @dev Emitted by successful `requestImplChange` calls.
event ImplChangeRequested(
bytes32 _lockId,
address _msgSender,
address _proposedImpl
);
/// @dev Emitted by successful `confirmImplChange` calls.
event ImplChangeConfirmed(bytes32 _lockId, address _newImpl);
}
/** @title Public interface to ERC20 compliant token.
*
* @notice This contract is a permanent entry point to an ERC20 compliant
* system of contracts.
*
* @dev This contract contains no business logic and instead
* delegates to an instance of ERC20Impl. This contract also has no storage
* that constitutes the operational state of the token. This contract is
* upgradeable in the sense that the `custodian` can update the
* `erc20Impl` address, thus redirecting the delegation of business logic.
* The `custodian` is also authorized to pass custodianship.
*
*/
contract ERC20Proxy is ERC20Interface, ERC20ImplUpgradeable {
// MEMBERS
/// @notice Returns the name of the token.
string public name;
/// @notice Returns the symbol of the token.
string public symbol;
/// @notice Returns the number of decimals the token uses.
uint8 public decimals;
// CONSTRUCTOR
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _custodian
)
ERC20ImplUpgradeable(_custodian)
public
{
name = _name;
symbol = _symbol;
decimals = _decimals;
}
// PUBLIC FUNCTIONS
// (ERC20Interface)
/** @notice Returns the total token supply.
*
* @return the total token supply.
*/
function totalSupply() public view returns (uint256) {
return erc20Impl.totalSupply();
}
/** @notice Returns the account balance of another account with an address
* `_owner`.
*
* @return balance the balance of account with address `_owner`.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Impl.balanceOf(_owner);
}
/** @dev Internal use only.
*/
function emitTransfer(address _from, address _to, uint256 _value) public onlyImpl {
emit Transfer(_from, _to, _value);
}
/** @notice Transfers `_value` amount of tokens to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert if the `_from`
* account balance does not have enough tokens to spend.
*
* @return success true if transfer completes.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
return erc20Impl.transferWithSender(msg.sender, _to, _value);
}
/** @notice Transfers `_value` amount of tokens from address `_from`
* to address `_to`.
*
* @dev Will fire the `Transfer` event. Will revert unless the `_from`
* account has deliberately authorized the sender of the message
* via some mechanism.
*
* @return success true if transfer completes.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
return erc20Impl.transferFromWithSender(msg.sender, _from, _to, _value);
}
/** @dev Internal use only.
*/
function emitApproval(address _owner, address _spender, uint256 _value) public onlyImpl {
emit Approval(_owner, _spender, _value);
}
/** @notice Allows `_spender` to withdraw from your account multiple times,
* up to the `_value` amount. If this function is called again it
* overwrites the current allowance with _value.
*
* @dev Will fire the `Approval` event.
*
* @return success true if approval completes.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
return erc20Impl.approveWithSender(msg.sender, _spender, _value);
}
/** @notice Increases the amount `_spender` is allowed to withdraw from
* your account.
* This function is implemented to avoid the race condition in standard
* ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used instead of
* `approve`.
*
* @return success true if approval completes.
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool success) {
return erc20Impl.increaseApprovalWithSender(msg.sender, _spender, _addedValue);
}
/** @notice Decreases the amount `_spender` is allowed to withdraw from
* your account. This function is implemented to avoid the race
* condition in standard ERC20 contracts surrounding the `approve` method.
*
* @dev Will fire the `Approval` event. This function should be used
* instead of `approve`.
*
* @return success true if approval completes.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public returns (bool success) {
return erc20Impl.decreaseApprovalWithSender(msg.sender, _spender, _subtractedValue);
}
/** @notice Returns how much `_spender` is currently allowed to spend from
* `_owner`'s balance.
*
* @return remaining the remaining allowance.
*/
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Impl.allowance(_owner, _spender);
}
}
/** @title ERC20 compliant token balance store.
*
* @notice This contract serves as the store of balances, allowances, and
* supply for the ERC20 compliant token. No business logic exists here.
*
* @dev This contract contains no business logic and instead
* is the final destination for any change in balances, allowances, or token
* supply. This contract is upgradeable in the sense that its custodian can
* update the `erc20Impl` address, thus redirecting the source of logic that
* determines how the balances will be updated.
*
*/
contract ERC20Store is ERC20ImplUpgradeable {
// MEMBERS
/// @dev The total token supply.
uint256 public totalSupply;
/// @dev The mapping of balances.
mapping (address => uint256) public balances;
/// @dev The mapping of allowances.
mapping (address => mapping (address => uint256)) public allowed;
// CONSTRUCTOR
constructor(address _custodian) ERC20ImplUpgradeable(_custodian) public {
totalSupply = 0;
}
// PUBLIC FUNCTIONS
// (ERC20 Ledger)
/** @notice The function to set the total supply of tokens.
*
* @dev Intended for use by token implementation functions
* that update the total supply. The only authorized caller
* is the active implementation.
*
* @param _newTotalSupply the value to set as the new total supply
*/
function setTotalSupply(
uint256 _newTotalSupply
)
public
onlyImpl
{
totalSupply = _newTotalSupply;
}
/** @notice Sets how much `_owner` allows `_spender` to transfer on behalf
* of `_owner`.
*
* @dev Intended for use by token implementation functions
* that update spending allowances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will allow an on-behalf-of spend.
* @param _spender The account that will spend on behalf of the owner.
* @param _value The limit of what can be spent.
*/
function setAllowance(
address _owner,
address _spender,
uint256 _value
)
public
onlyImpl
{
allowed[_owner][_spender] = _value;
}
/** @notice Sets the balance of `_owner` to `_newBalance`.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
*
* @param _owner The account that will hold a new balance.
* @param _newBalance The balance to set.
*/
function setBalance(
address _owner,
uint256 _newBalance
)
public
onlyImpl
{
balances[_owner] = _newBalance;
}
/** @notice Adds `_balanceIncrease` to `_owner`'s balance.
*
* @dev Intended for use by token implementation functions
* that update balances. The only authorized caller
* is the active implementation.
* WARNING: the caller is responsible for preventing overflow.
*
* @param _owner The account that will hold a new balance.
* @param _balanceIncrease The balance to add.
*/
function addBalance(
address _owner,
uint256 _balanceIncrease
)
public
onlyImpl
{
balances[_owner] = balances[_owner] + _balanceIncrease;
}
}
/** @title ERC20 compliant token intermediary contract holding core logic.
*
* @notice This contract serves as an intermediary between the exposed ERC20
* interface in ERC20Proxy and the store of balances in ERC20Store. This
* contract contains core logic that the proxy can delegate to
* and that the store is called by.
*
* @dev This contract contains the core logic to implement the
* ERC20 specification as well as several extensions.
* 1. Changes to the token supply.
* 2. Batched transfers.
* 3. Relative changes to spending approvals.
* 4. Delegated transfer control ('sweeping').
*
*/
contract ERC20Impl is CustodianUpgradeable {
// TYPES
/// @dev The struct type for pending increases to the token supply (print).
struct PendingPrint {
address receiver;
uint256 value;
}
// MEMBERS
/// @dev The reference to the proxy.
ERC20Proxy public erc20Proxy;
/// @dev The reference to the store.
ERC20Store public erc20Store;
/// @dev The sole authorized caller of delegated transfer control ('sweeping').
address public sweeper;
/** @dev The static message to be signed by an external account that
* signifies their permission to forward their balance to any arbitrary
* address. This is used to consolidate the control of all accounts
* backed by a shared keychain into the control of a single key.
* Initialized as the concatenation of the address of this contract
* and the word "sweep". This concatenation is done to prevent a replay
* attack in a subsequent contract, where the sweeping message could
* potentially be replayed to re-enable sweeping ability.
*/
bytes32 public sweepMsg;
/** @dev The mapping that stores whether the address in question has
* enabled sweeping its contents to another account or not.
* If an address maps to "true", it has already enabled sweeping,
* and thus does not need to re-sign the `sweepMsg` to enact the sweep.
*/
mapping (address => bool) public sweptSet;
/// @dev The map of lock ids to pending token increases.
mapping (bytes32 => PendingPrint) public pendingPrintMap;
/// @dev The map of blocked addresses.
mapping (address => bool) public blocked;
// CONSTRUCTOR
constructor(
address _erc20Proxy,
address _erc20Store,
address _custodian,
address _sweeper
)
CustodianUpgradeable(_custodian)
public
{
require(_sweeper != address(0), "no null value for `_sweeper`");
erc20Proxy = ERC20Proxy(_erc20Proxy);
erc20Store = ERC20Store(_erc20Store);
sweeper = _sweeper;
sweepMsg = keccak256(abi.encodePacked(address(this), "sweep"));
}
// MODIFIERS
modifier onlyProxy {
require(msg.sender == address(erc20Proxy), "only ERC20Proxy");
_;
}
modifier onlySweeper {
require(msg.sender == sweeper, "only sweeper");
_;
}
/** @notice Core logic of the ERC20 `approve` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `approve` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval in a proxy.
*/
function approveWithSender(
address _sender,
address _spender,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0), "no null value for `_spender`");
require(blocked[_sender] != true, "_sender must not be blocked");
require(blocked[_spender] != true, "_spender must not be blocked");
erc20Store.setAllowance(_sender, _spender, _value);
erc20Proxy.emitApproval(_sender, _spender, _value);
return true;
}
/** @notice Core logic of the `increaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has an `increaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function increaseApprovalWithSender(
address _sender,
address _spender,
uint256 _addedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0),"no null value for_spender");
require(blocked[_sender] != true, "_sender must not be blocked");
require(blocked[_spender] != true, "_spender must not be blocked");
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance + _addedValue;
require(newAllowance >= currentAllowance, "new allowance must not be smaller than previous");
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Core logic of the `decreaseApproval` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `decreaseApproval` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: approvals for the zero address (unspendable) are disallowed.
*
* @param _sender The address initiating the approval.
*/
function decreaseApprovalWithSender(
address _sender,
address _spender,
uint256 _subtractedValue
)
public
onlyProxy
returns (bool success)
{
require(_spender != address(0), "no unspendable approvals"); // disallow unspendable approvals
require(blocked[_sender] != true, "_sender must not be blocked");
require(blocked[_spender] != true, "_spender must not be blocked");
uint256 currentAllowance = erc20Store.allowed(_sender, _spender);
uint256 newAllowance = currentAllowance - _subtractedValue;
require(newAllowance <= currentAllowance, "new allowance must not be smaller than previous");
erc20Store.setAllowance(_sender, _spender, newAllowance);
erc20Proxy.emitApproval(_sender, _spender, newAllowance);
return true;
}
/** @notice Requests an increase in the token supply, with the newly created
* tokens to be added to the balance of the specified account.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print, if confirmed.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address, if confirmed.
*
* @return lockId A unique identifier for this request.
*/
function requestPrint(address _receiver, uint256 _value) public returns (bytes32 lockId) {
require(_receiver != address(0), "no null value for `_receiver`");
require(blocked[msg.sender] != true, "account blocked");
require(blocked[_receiver] != true, "_receiver must not be blocked");
lockId = generateLockId();
pendingPrintMap[lockId] = PendingPrint({
receiver: _receiver,
value: _value
});
emit PrintingLocked(lockId, _receiver, _value);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending increase, the amount requested to be printed in the print request
* is printed to the receiving address specified in that same request.
* NOTE: this function will not execute any print that would overflow the
* total supply, but it will not revert either.
*
* @param _lockId The identifier of a pending print request.
*/
function confirmPrint(bytes32 _lockId) public onlyCustodian {
PendingPrint storage print = pendingPrintMap[_lockId];
// reject 1null1 results from the map lookup
// this can only be the case if an unknown `_lockId` is received
address receiver = print.receiver;
require (receiver != address(0), "unknown `_lockId`");
uint256 value = print.value;
delete pendingPrintMap[_lockId];
uint256 supply = erc20Store.totalSupply();
uint256 newSupply = supply + value;
if (newSupply >= supply) {
erc20Store.setTotalSupply(newSupply);
erc20Store.addBalance(receiver, value);
emit PrintingConfirmed(_lockId, receiver, value);
erc20Proxy.emitTransfer(address(0), receiver, value);
}
}
/** @notice Burns the specified value from the sender's balance.
*
* @dev Sender's balanced is subtracted by the amount they wish to burn.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(uint256 _value) public returns (bool success) {
require(blocked[msg.sender] != true, "account blocked");
uint256 balanceOfSender = erc20Store.balances(msg.sender);
require(_value <= balanceOfSender, "disallow burning more, than amount of the balance");
erc20Store.setBalance(msg.sender, balanceOfSender - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(msg.sender, address(0), _value);
return true;
}
/** @notice Burns the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be burnt.
*
* @dev If the suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to burn.
*
* @return success true if the burn succeeded.
*/
function burn(address _from, uint256 _value) public onlyCustodian returns (bool success) {
uint256 balance = erc20Store.balances(_from);
if(_value <= balance){
erc20Store.setBalance(_from, balance - _value);
erc20Store.setTotalSupply(erc20Store.totalSupply() - _value);
erc20Proxy.emitTransfer(_from, address(0), _value);
emit Wiped(_from, _value, _value, balance - _value);
}
else {
erc20Store.setBalance(_from,0);
erc20Store.setTotalSupply(erc20Store.totalSupply() - balance);
erc20Proxy.emitTransfer(_from, address(0), balance);
emit Wiped(_from, _value, balance, 0);
}
return true;
}
/** @notice A function for a sender to issue multiple transfers to multiple
* different addresses at once. This function is implemented for gas
* considerations when someone wishes to transfer, as one transaction is
* cheaper than issuing several distinct individual `transfer` transactions.
*
* @dev By specifying a set of destination addresses and values, the
* sender can issue one transaction to transfer multiple amounts to
* distinct addresses, rather than issuing each as a separate
* transaction. The `_tos` and `_values` arrays must be equal length, and
* an index in one array corresponds to the same index in the other array
* (e.g. `_tos[0]` will receive `_values[0]`, `_tos[1]` will receive
* `_values[1]`, and so on.)
* NOTE: transfers to the zero address are disallowed.
*
* @param _tos The destination addresses to receive the transfers.
* @param _values The values for each destination address.
* @return success If transfers succeeded.
*/
function batchTransfer(address[] memory _tos, uint256[] memory _values) public returns (bool success) {
require(_tos.length == _values.length, "_tos and _values must be the same length");
require(blocked[msg.sender] != true, "account blocked");
uint256 numTransfers = _tos.length;
uint256 senderBalance = erc20Store.balances(msg.sender);
for (uint256 i = 0; i < numTransfers; i++) {
address to = _tos[i];
require(to != address(0), "no null values for _tos");
require(blocked[to] != true, "_tos must not be blocked");
uint256 v = _values[i];
require(senderBalance >= v, "insufficient funds");
if (msg.sender != to) {
senderBalance -= v;
erc20Store.addBalance(to, v);
}
erc20Proxy.emitTransfer(msg.sender, to, v);
}
erc20Store.setBalance(msg.sender, senderBalance);
return true;
}
/** @notice Enables the delegation of transfer control for many
* accounts to the sweeper account, transferring any balances
* as well to the given destination.
*
* @dev An account delegates transfer control by signing the
* value of `sweepMsg`. The sweeper account is the only authorized
* caller of this function, so it must relay signatures on behalf
* of accounts that delegate transfer control to it. Enabling
* delegation is idempotent and permanent. If the account has a
* balance at the time of enabling delegation, its balance is
* also transferred to the given destination account `_to`.
* NOTE: transfers to the zero address are disallowed.
*
* @param _vs The array of recovery byte components of the ECDSA signatures.
* @param _rs The array of 'R' components of the ECDSA signatures.
* @param _ss The array of 'S' components of the ECDSA signatures.
* @param _to The destination for swept balances.
*/
function enableSweep(uint8[] memory _vs, bytes32[] memory _rs, bytes32[] memory _ss, address _to) public onlySweeper {
require(_to != address(0), "no null value for `_to`");
require(blocked[_to] != true, "_to must not be blocked");
require((_vs.length == _rs.length) && (_vs.length == _ss.length), "_vs[], _rs[], _ss lengths are different");
uint256 numSignatures = _vs.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < numSignatures; ++i) {
address from = ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",sweepMsg)), _vs[i], _rs[i], _ss[i]);
require(blocked[from] != true, "_froms must not be blocked");
// ecrecover returns 0 on malformed input
if (from != address(0)) {
sweptSet[from] = true;
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice For accounts that have delegated, transfer control
* to the sweeper, this function transfers their balances to the given
* destination.
*
* @dev The sweeper account is the only authorized caller of
* this function. This function accepts an array of addresses to have their
* balances transferred for gas efficiency purposes.
* NOTE: any address for an account that has not been previously enabled
* will be ignored.
* NOTE: transfers to the zero address are disallowed.
*
* @param _froms The addresses to have their balances swept.
* @param _to The destination address of all these transfers.
*/
function replaySweep(address[] memory _froms, address _to) public onlySweeper {
require(_to != address(0), "no null value for `_to`");
require(blocked[_to] != true, "_to must not be blocked");
uint256 lenFroms = _froms.length;
uint256 sweptBalance = 0;
for (uint256 i = 0; i < lenFroms; ++i) {
address from = _froms[i];
require(blocked[from] != true, "_froms must not be blocked");
if (sweptSet[from]) {
uint256 fromBalance = erc20Store.balances(from);
if (fromBalance > 0) {
sweptBalance += fromBalance;
erc20Store.setBalance(from, 0);
erc20Proxy.emitTransfer(from, _to, fromBalance);
}
}
}
if (sweptBalance > 0) {
erc20Store.addBalance(_to, sweptBalance);
}
}
/** @notice Core logic of the ERC20 `transferFrom` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transferFrom` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in a proxy.
*/
function transferFromWithSender(
address _sender,
address _from,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0), "no null values for `_to`");
require(blocked[_sender] != true, "_sender must not be blocked");
require(blocked[_from] != true, "_from must not be blocked");
require(blocked[_to] != true, "_to must not be blocked");
uint256 balanceOfFrom = erc20Store.balances(_from);
require(_value <= balanceOfFrom, "insufficient funds on `_from` balance");
uint256 senderAllowance = erc20Store.allowed(_from, _sender);
require(_value <= senderAllowance, "insufficient allowance amount");
erc20Store.setBalance(_from, balanceOfFrom - _value);
erc20Store.addBalance(_to, _value);
erc20Store.setAllowance(_from, _sender, senderAllowance - _value);
erc20Proxy.emitTransfer(_from, _to, _value);
return true;
}
/** @notice Core logic of the ERC20 `transfer` function.
*
* @dev This function can only be called by the referenced proxy,
* which has a `transfer` function.
* Every argument passed to that function as well as the original
* `msg.sender` gets passed to this function.
* NOTE: transfers to the zero address are disallowed.
*
* @param _sender The address initiating the transfer in a proxy.
*/
function transferWithSender(
address _sender,
address _to,
uint256 _value
)
public
onlyProxy
returns (bool success)
{
require(_to != address(0), "no null value for `_to`");
require(blocked[_sender] != true, "_sender must not be blocked");
require(blocked[_to] != true, "_to must not be blocked");
uint256 balanceOfSender = erc20Store.balances(_sender);
require(_value <= balanceOfSender, "insufficient funds");
erc20Store.setBalance(_sender, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_sender, _to, _value);
return true;
}
/** @notice Transfers the specified value from the balance in question.
*
* @dev Suspected balance is subtracted by the amount which will be transferred.
*
* @dev If the suspected balance has less than the amount requested, it will be set to 0.
*
* @param _from The address of suspected balance.
*
* @param _value The amount to transfer.
*
* @return success true if the transfer succeeded.
*/
function forceTransfer(
address _from,
address _to,
uint256 _value
)
public
onlyCustodian
returns (bool success)
{
require(_to != address(0), "no null value for `_to`");
uint256 balanceOfSender = erc20Store.balances(_from);
if(_value <= balanceOfSender) {
erc20Store.setBalance(_from, balanceOfSender - _value);
erc20Store.addBalance(_to, _value);
erc20Proxy.emitTransfer(_from, _to, _value);
} else {
erc20Store.setBalance(_from, 0);
erc20Store.addBalance(_to, balanceOfSender);
erc20Proxy.emitTransfer(_from, _to, balanceOfSender);
}
return true;
}
// METHODS (ERC20 sub interface impl.)
/// @notice Core logic of the ERC20 `totalSupply` function.
function totalSupply() public view returns (uint256) {
return erc20Store.totalSupply();
}
/// @notice Core logic of the ERC20 `balanceOf` function.
function balanceOf(address _owner) public view returns (uint256 balance) {
return erc20Store.balances(_owner);
}
/// @notice Core logic of the ERC20 `allowance` function.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return erc20Store.allowed(_owner, _spender);
}
/// @dev internal use only.
function blockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = true;
return true;
}
/// @dev internal use only.
function unblockWallet(address wallet) public onlyCustodian returns (bool success) {
blocked[wallet] = false;
return true;
}
// EVENTS
/// @dev Emitted by successful `requestPrint` calls.
event PrintingLocked(bytes32 _lockId, address _receiver, uint256 _value);
/// @dev Emitted by successful `confirmPrint` calls.
event PrintingConfirmed(bytes32 _lockId, address _receiver, uint256 _value);
/** @dev Emitted by successful `confirmWipe` calls.
*
* @param _value Amount requested to be burned.
*
* @param _burned Amount which was burned.
*
* @param _balance Amount left on account after burn.
*
* @param _from Account which balance was burned.
*/
event Wiped(address _from, uint256 _value, uint256 _burned, uint _balance);
}
/** @title A contact to govern hybrid control over increases to the token supply and managing accounts.
*
* @notice A contract that acts as a custodian of the active token
* implementation, and an intermediary between it and the 1true1 custodian.
* It preserves the functionality of direct custodianship as well as granting
* limited control of token supply increases to an additional key.
*
* @dev This contract is a layer of indirection between an instance of
* ERC20Impl and a custodian. The functionality of the custodianship over
* the token implementation is preserved (printing and custodian changes),
* but this contract adds the ability for an additional key
* (the 'controller') to increase the token supply up to a ceiling,
* and this supply ceiling can only be raised by the custodian.
*
*/
contract Controller is LockRequestable {
// TYPES
/// @dev The struct type for pending ceiling raises.
struct PendingCeilingRaise {
uint256 raiseBy;
}
/// @dev The struct type for pending wipes.
struct wipeAddress {
uint256 value;
address from;
}
/// @dev The struct type for pending force transfer requests.
struct forceTransferRequest {
uint256 value;
address from;
address to;
}
// MEMBERS
/// @dev The reference to the active token implementation.
ERC20Impl public erc20Impl;
/// @dev The address of the account or contract that acts as the custodian.
Custodian public custodian;
/** @dev The sole authorized caller of limited printing.
* This account is also authorized to lower the supply ceiling and
* wiping suspected accounts or force transferring funds from them.
*/
address public controller;
/** @dev The maximum that the token supply can be increased to
* through the use of the limited printing feature.
* The difference between the current total supply and the supply
* ceiling is what is available to the 'controller' account.
* The value of the ceiling can only be increased by the custodian.
*/
uint256 public totalSupplyCeiling;
/// @dev The map of lock ids to pending ceiling raises.
mapping (bytes32 => PendingCeilingRaise) public pendingRaiseMap;
/// @dev The map of lock ids to pending wipes.
mapping (bytes32 => wipeAddress[]) public pendingWipeMap;
/// @dev The map of lock ids to pending force transfer requests.
mapping (bytes32 => forceTransferRequest) public pendingForceTransferRequestMap;
// CONSTRUCTOR
constructor(
address _erc20Impl,
address _custodian,
address _controller,
uint256 _initialCeiling
)
public
{
erc20Impl = ERC20Impl(_erc20Impl);
custodian = Custodian(_custodian);
controller = _controller;
totalSupplyCeiling = _initialCeiling;
}
// MODIFIERS
modifier onlyCustodian {
require(msg.sender == address(custodian), "only custodian");
_;
}
modifier onlyController {
require(msg.sender == controller, "only controller");
_;
}
modifier onlySigner {
require(custodian.signerSet(msg.sender) == true, "only signer");
_;
}
/** @notice Increases the token supply, with the newly created tokens
* being added to the balance of the specified account.
*
* @dev The function checks that the value to print does not
* exceed the supply ceiling when added to the current total supply.
* NOTE: printing to the zero address is disallowed.
*
* @param _receiver The receiving address of the print.
* @param _value The number of tokens to add to the total supply and the
* balance of the receiving address.
*/
function limitedPrint(address _receiver, uint256 _value) public onlyController {
uint256 totalSupply = erc20Impl.totalSupply();
uint256 newTotalSupply = totalSupply + _value;
require(newTotalSupply >= totalSupply, "new total supply overflow");
require(newTotalSupply <= totalSupplyCeiling, "total supply ceiling overflow");
erc20Impl.confirmPrint(erc20Impl.requestPrint(_receiver, _value));
}
/** @notice Requests wipe of suspected accounts.
*
* @dev Returns a unique lock id associated with the request.
* Only controller can call this function, and only the custodian
* can confirm the request.
*
* @param _froms The array of suspected accounts.
*
* @param _values array of amounts by which suspected accounts will be wiped.
*
* @return lockId A unique identifier for this request.
*/
function requestWipe(address[] memory _froms, uint256[] memory _values) public onlyController returns (bytes32 lockId) {
require(_froms.length == _values.length, "_froms[] and _values[] must be same length");
lockId = generateLockId();
uint256 amount = _froms.length;
for(uint256 i = 0; i < amount; i++) {
address from = _froms[i];
uint256 value = _values[i];
pendingWipeMap[lockId].push(wipeAddress(value, from));
}
emit WipeRequested(lockId);
return lockId;
}
/** @notice Confirms a pending wipe of suspected accounts.
*
* @dev When called by the custodian with a lock id associated with a
* pending wipe, the amount requested is burned from the suspected accounts.
*
* @param _lockId The identifier of a pending wipe request.
*/
function confirmWipe(bytes32 _lockId) public onlyCustodian {
uint256 amount = pendingWipeMap[_lockId].length;
for(uint256 i = 0; i < amount; i++) {
wipeAddress memory addr = pendingWipeMap[_lockId][i];
address from = addr.from;
uint256 value = addr.value;
erc20Impl.burn(from, value);
}
delete pendingWipeMap[_lockId];
emit WipeCompleted(_lockId);
}
/** @notice Requests force transfer from the suspected account.
*
* @dev Returns a unique lock id associated with the request.
* Only controller can call this function, and only the custodian
* can confirm the request.
*
* @param _from address of suspected account.
*
* @param _to address of reciever.
*
* @param _value amount which will be transferred.
*
* @return lockId A unique identifier for this request.
*/
function requestForceTransfer(address _from, address _to, uint256 _value) public onlyController returns (bytes32 lockId) {
lockId = generateLockId();
require (_value != 0, "no zero value transfers");
pendingForceTransferRequestMap[lockId] = forceTransferRequest(_value, _from, _to);
emit ForceTransferRequested(lockId, _from, _to, _value);
return lockId;
}
/** @notice Confirms a pending force transfer request.
*
* @dev When called by the custodian with a lock id associated with a
* pending transfer request, the amount requested is transferred from the suspected account.
*
* @param _lockId The identifier of a pending transfer request.
*/
function confirmForceTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingForceTransferRequestMap[_lockId].from;
address to = pendingForceTransferRequestMap[_lockId].to;
uint256 value = pendingForceTransferRequestMap[_lockId].value;
delete pendingForceTransferRequestMap[_lockId];
erc20Impl.forceTransfer(from, to, value);
emit ForceTransferCompleted(_lockId, from, to, value);
}
/** @notice Requests an increase to the supply ceiling.
*
* @dev Returns a unique lock id associated with the request.
* Anyone can call this function, but confirming the request is authorized
* by the custodian.
*
* @param _raiseBy The amount by which to raise the ceiling.
*
* @return lockId A unique identifier for this request.
*/
function requestCeilingRaise(uint256 _raiseBy) public returns (bytes32 lockId) {
require(_raiseBy != 0, "no zero ceiling raise");
lockId = generateLockId();
pendingRaiseMap[lockId] = PendingCeilingRaise({
raiseBy: _raiseBy
});
emit CeilingRaiseLocked(lockId, _raiseBy);
}
/** @notice Confirms a pending increase in the token supply.
*
* @dev When called by the custodian with a lock id associated with a
* pending ceiling increase, the amount requested is added to the
* current supply ceiling.
* NOTE: this function will not execute any raise that would overflow the
* supply ceiling, but it will not revert either.
*
* @param _lockId The identifier of a pending ceiling raise request.
*/
function confirmCeilingRaise(bytes32 _lockId) public onlyCustodian {
PendingCeilingRaise storage pendingRaise = pendingRaiseMap[_lockId];
// copy locals of references to struct members
uint256 raiseBy = pendingRaise.raiseBy;
// accounts for a gibberish _lockId
require(raiseBy != 0, "no gibberish _lockId");
delete pendingRaiseMap[_lockId];
uint256 newCeiling = totalSupplyCeiling + raiseBy;
// overflow check
if (newCeiling >= totalSupplyCeiling) {
totalSupplyCeiling = newCeiling;
emit CeilingRaiseConfirmed(_lockId, raiseBy, newCeiling);
}
}
/** @notice Lowers the supply ceiling, further constraining the bound of
* what can be printed by the controller.
*
* @dev The controller is the sole authorized caller of this function,
* so it is the only account that can elect to lower its limit to increase
* the token supply.
*
* @param _lowerBy The amount by which to lower the supply ceiling.
*/
function lowerCeiling(uint256 _lowerBy) public onlyController {
uint256 newCeiling = totalSupplyCeiling - _lowerBy;
// overflow check
require(newCeiling <= totalSupplyCeiling, "totalSupplyCeiling overflow");
totalSupplyCeiling = newCeiling;
emit CeilingLowered(_lowerBy, newCeiling);
}
/** @notice Pass-through control of print confirmation, allowing this
* contract's custodian to act as the custodian of the associated
* active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* unlimited printing.
*
* @param _lockId The identifier of a pending print request in
* the associated active token implementation.
*/
function confirmPrintProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmPrint(_lockId);
}
/** @notice Pass-through control of custodian change confirmation,
* allowing this contract's custodian to act as the custodian of
* the associated active token implementation.
*
* @dev This contract is the direct custodian of the active token
* implementation, but this function allows this contract's custodian
* to act as though it were the direct custodian of the active
* token implementation. Therefore the custodian retains control of
* custodian changes.
*
* @param _lockId The identifier of a pending custodian change request
* in the associated active token implementation.
*/
function confirmCustodianChangeProxy(bytes32 _lockId) public onlyCustodian {
erc20Impl.confirmCustodianChange(_lockId);
}
/** @notice Blocks all transactions with a wallet.
*
* @dev Only signers from custodian are authorized to call this function
*
* @param wallet account which will be blocked.
*/
function blockWallet(address wallet) public onlySigner {
erc20Impl.blockWallet(wallet);
emit Blocked(wallet);
}
/** @notice Unblocks all transactions with a wallet.
*
* @dev Only signers from custodian are authorized to call this function
*
* @param wallet account which will be unblocked.
*/
function unblockWallet(address wallet) public onlySigner {
erc20Impl.unblockWallet(wallet);
emit Unblocked(wallet);
}
// EVENTS
/// @dev Emitted by successful `requestCeilingRaise` calls.
event CeilingRaiseLocked(bytes32 _lockId, uint256 _raiseBy);
/// @dev Emitted by successful `confirmCeilingRaise` calls.
event CeilingRaiseConfirmed(bytes32 _lockId, uint256 _raiseBy, uint256 _newCeiling);
/// @dev Emitted by successful `lowerCeiling` calls.
event CeilingLowered(uint256 _lowerBy, uint256 _newCeiling);
/// @dev Emitted by successful `blockWallet` calls.
event Blocked(address _wallet);
/// @dev Emitted by successful `unblockWallet` calls.
event Unblocked(address _wallet);
/// @dev Emitted by successful `requestForceTransfer` calls.
event ForceTransferRequested(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `confirmForceTransfer` calls.
event ForceTransferCompleted(bytes32 _lockId, address _from, address _to, uint256 _value);
/// @dev Emitted by successful `requestWipe` calls.
event WipeRequested(bytes32 _lockId);
/// @dev Emitted by successful `confirmWipe` calls.
event WipeCompleted(bytes32 _lockId);
} | * @notice Confirms a pending force transfer request. @dev When called by the custodian with a lock id associated with a pending transfer request, the amount requested is transferred from the suspected account. @param _lockId The identifier of a pending transfer request./ | function confirmForceTransfer(bytes32 _lockId) public onlyCustodian {
address from = pendingForceTransferRequestMap[_lockId].from;
address to = pendingForceTransferRequestMap[_lockId].to;
uint256 value = pendingForceTransferRequestMap[_lockId].value;
delete pendingForceTransferRequestMap[_lockId];
erc20Impl.forceTransfer(from, to, value);
emit ForceTransferCompleted(_lockId, from, to, value);
}
| 12,961,589 | [
1,
3976,
481,
959,
279,
4634,
2944,
7412,
590,
18,
282,
5203,
2566,
635,
326,
276,
641,
369,
2779,
598,
279,
2176,
612,
3627,
598,
279,
4634,
7412,
590,
16,
326,
3844,
3764,
353,
906,
4193,
628,
326,
11375,
1789,
2236,
18,
282,
389,
739,
548,
225,
1021,
2756,
434,
279,
4634,
7412,
590,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6932,
10997,
5912,
12,
3890,
1578,
389,
739,
548,
13,
1071,
1338,
39,
641,
369,
2779,
288,
203,
3639,
1758,
628,
273,
4634,
10997,
5912,
691,
863,
63,
67,
739,
548,
8009,
2080,
31,
203,
3639,
1758,
358,
273,
4634,
10997,
5912,
691,
863,
63,
67,
739,
548,
8009,
869,
31,
203,
3639,
2254,
5034,
460,
273,
4634,
10997,
5912,
691,
863,
63,
67,
739,
548,
8009,
1132,
31,
203,
203,
3639,
1430,
4634,
10997,
5912,
691,
863,
63,
67,
739,
548,
15533,
203,
203,
3639,
6445,
71,
3462,
2828,
18,
5734,
5912,
12,
2080,
16,
358,
16,
460,
1769,
203,
203,
3639,
3626,
11889,
5912,
9556,
24899,
739,
548,
16,
628,
16,
358,
16,
460,
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
] |
pragma solidity 0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint a, uint b) internal pure returns(uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint a, uint b) internal pure returns(uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint a, uint b) internal pure returns(uint) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint a, uint b) internal pure returns(uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Dieter Shirley <[email protected]> (https://github.com/dete)
contract ERC721 {
// Required methods
function approve(address _to, uint _tokenId) public;
function balanceOf(address _owner) public view returns(uint balance);
function implementsERC721() public pure returns(bool);
function ownerOf(uint _tokenId) public view returns(address addr);
function takeOwnership(uint _tokenId) public;
function totalSupply() public view returns(uint total);
function transferFrom(address _from, address _to, uint _tokenId) public;
function transfer(address _to, uint _tokenId) public;
//event Transfer(uint tokenId, address indexed from, address indexed to);
event Approval(uint tokenId, address indexed owner, address indexed approved);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokenOfOwnerByIndex(address _owner, uint _index) external view returns (uint tokenId);
// function tokenMetadata(uint _tokenId) public view returns (string infoUrl);
}
contract CryptoCovfefes is ERC721 {
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant NAME = "CryptoCovfefes";
string public constant SYMBOL = "Covfefe Token";
uint private constant startingPrice = 0.001 ether;
uint private constant PROMO_CREATION_LIMIT = 5000;
uint private constant CONTRACT_CREATION_LIMIT = 45000;
uint private constant SaleCooldownTime = 12 hours;
uint private randNonce = 0;
uint private constant duelVictoryProbability = 51;
uint private constant duelFee = .001 ether;
uint private addMeaningFee = .001 ether;
/*** EVENTS ***/
/// @dev The Creation event is fired whenever a new Covfefe comes into existence.
event NewCovfefeCreated(uint tokenId, string term, string meaning, uint generation, address owner);
/// @dev The Meaning added event is fired whenever a Covfefe is defined
event CovfefeMeaningAdded(uint tokenId, string term, string meaning);
/// @dev The CovfefeSold event is fired whenever a token is bought and sold.
event CovfefeSold(uint tokenId, string term, string meaning, uint generation, uint sellingpPice, uint currentPrice, address buyer, address seller);
/// @dev The Add Value To Covfefe event is fired whenever value is added to the Covfefe token
event AddedValueToCovfefe(uint tokenId, string term, string meaning, uint generation, uint currentPrice);
/// @dev The Transfer Covfefe event is fired whenever a Covfefe token is transferred
event CovfefeTransferred(uint tokenId, address from, address to);
/// @dev The ChallengerWinsCovfefeDuel event is fired whenever the Challenging Covfefe wins a duel
event ChallengerWinsCovfefeDuel(uint tokenIdChallenger, string termChallenger, uint tokenIdDefender, string termDefender);
/// @dev The DefenderWinsCovfefeDuel event is fired whenever the Challenging Covfefe wins a duel
event DefenderWinsCovfefeDuel(uint tokenIdDefender, string termDefender, uint tokenIdChallenger, string termChallenger);
/*** STORAGE ***/
/// @dev A mapping from covfefe IDs to the address that owns them. All covfefes have
/// some valid owner address.
mapping(uint => address) public covfefeIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping(address => uint) private ownershipTokenCount;
/// @dev A mapping from CovfefeIDs to an address that has been approved to call
/// transferFrom(). Each Covfefe can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping(uint => address) public covfefeIndexToApproved;
// @dev A mapping from CovfefeIDs to the price of the token.
mapping(uint => uint) private covfefeIndexToPrice;
// @dev A mapping from CovfefeIDs to the price of the token.
mapping(uint => uint) private covfefeIndexToLastPrice;
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public covmanAddress;
address public covmanagerAddress;
uint public promoCreatedCount;
uint public contractCreatedCount;
/*** DATATYPES ***/
struct Covfefe {
string term;
string meaning;
uint16 generation;
uint16 winCount;
uint16 lossCount;
uint64 saleReadyTime;
}
Covfefe[] private covfefes;
/*** ACCESS MODIFIERS ***/
/// @dev Access modifier for Covman-only functionality
modifier onlyCovman() {
require(msg.sender == covmanAddress);
_;
}
/// @dev Access modifier for Covmanager-only functionality
modifier onlyCovmanager() {
require(msg.sender == covmanagerAddress);
_;
}
/// Access modifier for contract owner only functionality
modifier onlyCovDwellers() {
require(msg.sender == covmanAddress || msg.sender == covmanagerAddress);
_;
}
/*** CONSTRUCTOR ***/
function CryptoCovfefes() public {
covmanAddress = msg.sender;
covmanagerAddress = msg.sender;
}
/*** PUBLIC FUNCTIONS ***/
/// @notice Grant another address the right to transfer token via takeOwnership() and transferFrom().
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(address _to, uint _tokenId) public {
// Caller must own token.
require(_owns(msg.sender, _tokenId));
covfefeIndexToApproved[_tokenId] = _to;
emit Approval(_tokenId, msg.sender, _to);
}
/// For querying balance of a particular account
/// @param _owner The address for balance query
/// @dev Required for ERC-721 compliance.
function balanceOf(address _owner) public view returns(uint balance) {
return ownershipTokenCount[_owner];
}
///////////////////Create Covfefe///////////////////////////
/// @dev Creates a new promo Covfefe with the given term, with given _price and assignes it to an address.
function createPromoCovfefe(address _owner, string _term, string _meaning, uint16 _generation, uint _price) public onlyCovmanager {
require(promoCreatedCount < PROMO_CREATION_LIMIT);
address covfefeOwner = _owner;
if (covfefeOwner == address(0)) {
covfefeOwner = covmanagerAddress;
}
if (_price <= 0) {
_price = startingPrice;
}
promoCreatedCount++;
_createCovfefe(_term, _meaning, _generation, covfefeOwner, _price);
}
/// @dev Creates a new Covfefe with the given term.
function createContractCovfefe(string _term, string _meaning, uint16 _generation) public onlyCovmanager {
require(contractCreatedCount < CONTRACT_CREATION_LIMIT);
contractCreatedCount++;
_createCovfefe(_term, _meaning, _generation, address(this), startingPrice);
}
function _triggerSaleCooldown(Covfefe storage _covfefe) internal {
_covfefe.saleReadyTime = uint64(now + SaleCooldownTime);
}
function _ripeForSale(Covfefe storage _covfefe) internal view returns(bool) {
return (_covfefe.saleReadyTime <= now);
}
/// @notice Returns all the relevant information about a specific covfefe.
/// @param _tokenId The tokenId of the covfefe of interest.
function getCovfefe(uint _tokenId) public view returns(string Term, string Meaning, uint Generation, uint ReadyTime, uint WinCount, uint LossCount, uint CurrentPrice, uint LastPrice, address Owner) {
Covfefe storage covfefe = covfefes[_tokenId];
Term = covfefe.term;
Meaning = covfefe.meaning;
Generation = covfefe.generation;
ReadyTime = covfefe.saleReadyTime;
WinCount = covfefe.winCount;
LossCount = covfefe.lossCount;
CurrentPrice = covfefeIndexToPrice[_tokenId];
LastPrice = covfefeIndexToLastPrice[_tokenId];
Owner = covfefeIndexToOwner[_tokenId];
}
function implementsERC721() public pure returns(bool) {
return true;
}
/// @dev Required for ERC-721 compliance.
function name() public pure returns(string) {
return NAME;
}
/// For querying owner of token
/// @param _tokenId The tokenID for owner inquiry
/// @dev Required for ERC-721 compliance.
function ownerOf(uint _tokenId)
public
view
returns(address owner) {
owner = covfefeIndexToOwner[_tokenId];
require(owner != address(0));
}
modifier onlyOwnerOf(uint _tokenId) {
require(msg.sender == covfefeIndexToOwner[_tokenId]);
_;
}
///////////////////Add Meaning /////////////////////
function addMeaningToCovfefe(uint _tokenId, string _newMeaning) external payable onlyOwnerOf(_tokenId) {
/// Making sure the transaction is not from another smart contract
require(!isContract(msg.sender));
/// Making sure the addMeaningFee is included
require(msg.value == addMeaningFee);
/// Add the new meaning
covfefes[_tokenId].meaning = _newMeaning;
/// Emit the term meaning added event.
emit CovfefeMeaningAdded(_tokenId, covfefes[_tokenId].term, _newMeaning);
}
function payout(address _to) public onlyCovDwellers {
_payout(_to);
}
/////////////////Buy Token ////////////////////
// Allows someone to send ether and obtain the token
function buyCovfefe(uint _tokenId) public payable {
address oldOwner = covfefeIndexToOwner[_tokenId];
address newOwner = msg.sender;
// Making sure sale cooldown is not in effect
Covfefe storage myCovfefe = covfefes[_tokenId];
require(_ripeForSale(myCovfefe));
// Making sure the transaction is not from another smart contract
require(!isContract(msg.sender));
covfefeIndexToLastPrice[_tokenId] = covfefeIndexToPrice[_tokenId];
uint sellingPrice = covfefeIndexToPrice[_tokenId];
// Making sure token owner is not sending to self
require(oldOwner != newOwner);
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure sent amount is greater than or equal to the sellingPrice
require(msg.value >= sellingPrice);
uint payment = uint(SafeMath.div(SafeMath.mul(sellingPrice, 95), 100));
uint purchaseExcess = SafeMath.sub(msg.value, sellingPrice);
// Update prices
covfefeIndexToPrice[_tokenId] = SafeMath.div(SafeMath.mul(sellingPrice, 115), 95);
_transfer(oldOwner, newOwner, _tokenId);
///Trigger Sale cooldown
_triggerSaleCooldown(myCovfefe);
// Pay previous tokenOwner if owner is not contract
if (oldOwner != address(this)) {
oldOwner.transfer(payment); //(1-0.05)
}
emit CovfefeSold(_tokenId, covfefes[_tokenId].term, covfefes[_tokenId].meaning, covfefes[_tokenId].generation, covfefeIndexToLastPrice[_tokenId], covfefeIndexToPrice[_tokenId], newOwner, oldOwner);
msg.sender.transfer(purchaseExcess);
}
function priceOf(uint _tokenId) public view returns(uint price) {
return covfefeIndexToPrice[_tokenId];
}
function lastPriceOf(uint _tokenId) public view returns(uint price) {
return covfefeIndexToLastPrice[_tokenId];
}
/// @dev Assigns a new address to act as the Covman. Only available to the current Covman
/// @param _newCovman The address of the new Covman
function setCovman(address _newCovman) public onlyCovman {
require(_newCovman != address(0));
covmanAddress = _newCovman;
}
/// @dev Assigns a new address to act as the Covmanager. Only available to the current Covman
/// @param _newCovmanager The address of the new Covmanager
function setCovmanager(address _newCovmanager) public onlyCovman {
require(_newCovmanager != address(0));
covmanagerAddress = _newCovmanager;
}
/// @dev Required for ERC-721 compliance.
function symbol() public pure returns(string) {
return SYMBOL;
}
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint _tokenId) public {
address newOwner = msg.sender;
address oldOwner = covfefeIndexToOwner[_tokenId];
// Safety check to prevent against an unexpected 0x0 default.
require(_addressNotNull(newOwner));
// Making sure transfer is approved
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
///////////////////Add Value to Covfefe/////////////////////////////
//////////////There's no fee for adding value//////////////////////
function addValueToCovfefe(uint _tokenId) external payable onlyOwnerOf(_tokenId) {
// Making sure the transaction is not from another smart contract
require(!isContract(msg.sender));
//Making sure amount is within the min and max range
require(msg.value >= 0.001 ether);
require(msg.value <= 9999.000 ether);
//Keeping a record of lastprice before updating price
covfefeIndexToLastPrice[_tokenId] = covfefeIndexToPrice[_tokenId];
uint newValue = msg.value;
// Update prices
newValue = SafeMath.div(SafeMath.mul(newValue, 115), 100);
covfefeIndexToPrice[_tokenId] = SafeMath.add(newValue, covfefeIndexToPrice[_tokenId]);
///Emit the AddValueToCovfefe event
emit AddedValueToCovfefe(_tokenId, covfefes[_tokenId].term, covfefes[_tokenId].meaning, covfefes[_tokenId].generation, covfefeIndexToPrice[_tokenId]);
}
/// @param _owner The owner whose covfefe tokens we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Covfefes array looking for covfefes belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function getTokensOfOwner(address _owner) external view returns(uint[] ownerTokens) {
uint tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint[](0);
} else {
uint[] memory result = new uint[](tokenCount);
uint totalCovfefes = totalSupply();
uint resultIndex = 0;
uint covfefeId;
for (covfefeId = 0; covfefeId <= totalCovfefes; covfefeId++) {
if (covfefeIndexToOwner[covfefeId] == _owner) {
result[resultIndex] = covfefeId;
resultIndex++;
}
}
return result;
}
}
/// For querying totalSupply of token
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns(uint total) {
return covfefes.length;
}
/// Owner initates the transfer of the token to another account
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint _tokenId) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
/// Third-party initiates transfer of token from address _from to address _to
/// @param _from The address for the token to be transferred from.
/// @param _to The address for the token to be transferred to.
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function transferFrom(address _from, address _to, uint _tokenId) public {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
/*** PRIVATE FUNCTIONS ***/
/// Safety check on _to address to prevent against an unexpected 0x0 default.
function _addressNotNull(address _to) private pure returns(bool) {
return _to != address(0);
}
/// For checking approval of transfer for address _to
function _approved(address _to, uint _tokenId) private view returns(bool) {
return covfefeIndexToApproved[_tokenId] == _to;
}
/////////////Covfefe Creation////////////
function _createCovfefe(string _term, string _meaning, uint16 _generation, address _owner, uint _price) private {
Covfefe memory _covfefe = Covfefe({
term: _term,
meaning: _meaning,
generation: _generation,
saleReadyTime: uint64(now),
winCount: 0,
lossCount: 0
});
uint newCovfefeId = covfefes.push(_covfefe) - 1;
// It's probably never going to happen, 4 billion tokens are A LOT, but
// let's just be 100% sure we never let this happen.
require(newCovfefeId == uint(uint32(newCovfefeId)));
//Emit the Covfefe creation event
emit NewCovfefeCreated(newCovfefeId, _term, _meaning, _generation, _owner);
covfefeIndexToPrice[newCovfefeId] = _price;
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(address(0), _owner, newCovfefeId);
}
/// Check for token ownership
function _owns(address claimant, uint _tokenId) private view returns(bool) {
return claimant == covfefeIndexToOwner[_tokenId];
}
/// For paying out balance on contract
function _payout(address _to) private {
if (_to == address(0)) {
covmanAddress.transfer(address(this).balance);
} else {
_to.transfer(address(this).balance);
}
}
/////////////////////Transfer//////////////////////
/// @dev Transfer event as defined in current draft of ERC721.
/// ownership is assigned, including births.
/// @dev Assigns ownership of a specific Covfefe to an address.
function _transfer(address _from, address _to, uint _tokenId) private {
// Since the number of covfefes is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
//transfer ownership
covfefeIndexToOwner[_tokenId] = _to;
// When creating new covfefes _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete covfefeIndexToApproved[_tokenId];
}
// Emit the transfer event.
emit CovfefeTransferred(_tokenId, _from, _to);
}
///////////////////Covfefe Duel System//////////////////////
//Simple Randomizer for the covfefe duelling system
function randMod(uint _modulus) internal returns(uint) {
randNonce++;
return uint(keccak256(now, msg.sender, randNonce)) % _modulus;
}
function duelAnotherCovfefe(uint _tokenId, uint _targetId) external payable onlyOwnerOf(_tokenId) {
//Load the covfefes from storage
Covfefe storage myCovfefe = covfefes[_tokenId];
// Making sure the transaction is not from another smart contract
require(!isContract(msg.sender));
//Making sure the duelling fee is included
require(msg.value == duelFee);
//
Covfefe storage enemyCovfefe = covfefes[_targetId];
uint rand = randMod(100);
if (rand <= duelVictoryProbability) {
myCovfefe.winCount++;
enemyCovfefe.lossCount++;
///Emit the ChallengerWins event
emit ChallengerWinsCovfefeDuel(_tokenId, covfefes[_tokenId].term, _targetId, covfefes[_targetId].term);
} else {
myCovfefe.lossCount++;
enemyCovfefe.winCount++;
///Emit the DefenderWins event
emit DefenderWinsCovfefeDuel(_targetId, covfefes[_targetId].term, _tokenId, covfefes[_tokenId].term);
}
}
////////////////// Utility //////////////////
function isContract(address addr) internal view returns(bool) {
uint size;
assembly {
size: = extcodesize(addr)
}
return size > 0;
}
} | For querying totalSupply of token @dev Required for ERC-721 compliance. | function totalSupply() public view returns(uint total) {
return covfefes.length;
}
| 5,488,675 | [
1,
1290,
23936,
2078,
3088,
1283,
434,
1147,
225,
10647,
364,
4232,
39,
17,
27,
5340,
29443,
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,
2078,
3088,
1283,
1435,
1071,
1476,
1135,
12,
11890,
2078,
13,
288,
203,
3639,
327,
10613,
3030,
74,
281,
18,
2469,
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
] |
// Сочетаемость глаголов (и отглагольных частей речи) с предложным
// паттерном.
// LC->07.08.2018
facts гл_предл language=Russian
{
arity=3
//violation_score=-5
generic
return=boolean
}
#define ГЛ_ИНФ(v) инфинитив:v{}, глагол:v{}
#region Предлог_В
// ------------------- С ПРЕДЛОГОМ 'В' ---------------------------
#region Предложный
// Глаголы и отглагольные части речи, присоединяющие
// предложное дополнение с предлогом В и сущ. в предложном падеже.
wordentry_set Гл_В_Предл =
{
rus_verbs:взорваться{}, // В Дагестане взорвался автомобиль
// вернуть после перекомпиляции rus_verbs:подорожать{}, // В Дагестане подорожал хлеб
rus_verbs:воевать{}, // Воевал во Франции.
rus_verbs:устать{}, // Устали в дороге?
rus_verbs:изнывать{}, // В Лондоне Черчилль изнывал от нетерпения.
rus_verbs:решить{}, // Что решат в правительстве?
rus_verbs:выскакивать{}, // Один из бойцов на улицу выскакивает.
rus_verbs:обстоять{}, // В действительности же дело обстояло не так.
rus_verbs:подыматься{},
rus_verbs:поехать{}, // поедем в такси!
rus_verbs:уехать{}, // он уехал в такси
rus_verbs:прибыть{}, // они прибыли в качестве независимых наблюдателей
rus_verbs:ОБЛАЧИТЬ{},
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ПОВАЛЯТЬСЯ{}, // повалявшись в снегу, бежать обратно в тепло.
rus_verbs:ПОКРЫВАТЬ{}, // Во многих местах ее покрывали трещины, наросты и довольно плоские выступы. (ПОКРЫВАТЬ)
rus_verbs:ПРОЖИГАТЬ{}, // Синий луч искрился белыми пятнами и прожигал в земле дымящуюся борозду. (ПРОЖИГАТЬ)
rus_verbs:МЫЧАТЬ{}, // В огромной куче тел жалобно мычали задавленные трупами и раненые бизоны. (МЫЧАТЬ)
rus_verbs:РАЗБОЙНИЧАТЬ{}, // Эти существа обычно разбойничали в трехстах милях отсюда (РАЗБОЙНИЧАТЬ)
rus_verbs:МАЯЧИТЬ{}, // В отдалении маячили огромные серые туши мастодонтов и мамонтов с изогнутыми бивнями. (МАЯЧИТЬ/ЗАМАЯЧИТЬ)
rus_verbs:ЗАМАЯЧИТЬ{},
rus_verbs:НЕСТИСЬ{}, // Кони неслись вперед в свободном и легком галопе (НЕСТИСЬ)
rus_verbs:ДОБЫТЬ{}, // Они надеялись застать "медвежий народ" врасплох и добыть в бою голову величайшего из воинов. (ДОБЫТЬ)
rus_verbs:СПУСТИТЬ{}, // Время от времени грохот или вопль объявляли о спущенной где-то во дворце ловушке. (СПУСТИТЬ)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Она сузила глаза, на лице ее стала образовываться маска безумия. (ОБРАЗОВЫВАТЬСЯ)
rus_verbs:КИШЕТЬ{}, // в этом районе кишмя кишели разбойники и драконы. (КИШЕТЬ)
rus_verbs:ДЫШАТЬ{}, // Она тяжело дышала в тисках гнева (ДЫШАТЬ)
rus_verbs:ЗАДЕВАТЬ{}, // тот задевал в нем какую-то струну (ЗАДЕВАТЬ)
rus_verbs:УСТУПИТЬ{}, // Так что теперь уступи мне в этом. (УСТУПИТЬ)
rus_verbs:ТЕРЯТЬ{}, // Хотя он хорошо питался, он терял в весе (ТЕРЯТЬ/ПОТЕРЯТЬ)
rus_verbs:ПоТЕРЯТЬ{},
rus_verbs:УТЕРЯТЬ{},
rus_verbs:РАСТЕРЯТЬ{},
rus_verbs:СМЫКАТЬСЯ{}, // Словно медленно смыкающийся во сне глаз, отверстие медленно закрывалось. (СМЫКАТЬСЯ/СОМКНУТЬСЯ, + оборот с СЛОВНО/БУДТО + вин.п.)
rus_verbs:СОМКНУТЬСЯ{},
rus_verbs:РАЗВОРОШИТЬ{}, // Вольф не узнал никаких отдельных слов, но звуки и взаимодействующая высота тонов разворошили что-то в его памяти. (РАЗВОРОШИТЬ)
rus_verbs:ПРОСТОЯТЬ{}, // Он поднялся и некоторое время простоял в задумчивости. (ПРОСТОЯТЬ,ВЫСТОЯТЬ,ПОСТОЯТЬ)
rus_verbs:ВЫСТОЯТЬ{},
rus_verbs:ПОСТОЯТЬ{},
rus_verbs:ВЗВЕСИТЬ{}, // Он поднял и взвесил в руке один из рогов изобилия. (ВЗВЕСИТЬ/ВЗВЕШИВАТЬ)
rus_verbs:ВЗВЕШИВАТЬ{},
rus_verbs:ДРЕЙФОВАТЬ{}, // Он и тогда не упадет, а будет дрейфовать в отбрасываемой диском тени. (ДРЕЙФОВАТЬ)
прилагательное:быстрый{}, // Кисель быстр в приготовлении
rus_verbs:призвать{}, // В День Воли белорусов призвали побороть страх и лень
rus_verbs:призывать{},
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // этими деньгами смогу воспользоваться в отпуске (ВОСПОЛЬЗОВАТЬСЯ)
rus_verbs:КОНКУРИРОВАТЬ{}, // Наши клубы могли бы в Англии конкурировать с лидерами (КОНКУРИРОВАТЬ)
rus_verbs:ПОЗВАТЬ{}, // Американскую телеведущую позвали замуж в прямом эфире (ПОЗВАТЬ)
rus_verbs:ВЫХОДИТЬ{}, // Районные газеты Вологодчины будут выходить в цвете и новом формате (ВЫХОДИТЬ)
rus_verbs:РАЗВОРАЧИВАТЬСЯ{}, // Сюжет фэнтези разворачивается в двух мирах (РАЗВОРАЧИВАТЬСЯ)
rus_verbs:ОБСУДИТЬ{}, // В Самаре обсудили перспективы информатизации ветеринарии (ОБСУДИТЬ)
rus_verbs:ВЗДРОГНУТЬ{}, // она сильно вздрогнула во сне (ВЗДРОГНУТЬ)
rus_verbs:ПРЕДСТАВЛЯТЬ{}, // Сенаторы, представляющие в Комитете по разведке обе партии, поддержали эту просьбу (ПРЕДСТАВЛЯТЬ)
rus_verbs:ДОМИНИРОВАТЬ{}, // в химическом составе одной из планет доминирует метан (ДОМИНИРОВАТЬ)
rus_verbs:ОТКРЫТЬ{}, // Крым открыл в Москве собственный туристический офис (ОТКРЫТЬ)
rus_verbs:ПОКАЗАТЬ{}, // В Пушкинском музее показали золото инков (ПОКАЗАТЬ)
rus_verbs:наблюдать{}, // Наблюдаемый в отражении цвет излучения
rus_verbs:ПРОЛЕТЕТЬ{}, // Крупный астероид пролетел в непосредственной близости от Земли (ПРОЛЕТЕТЬ)
rus_verbs:РАССЛЕДОВАТЬ{}, // В Дагестане расследуют убийство федерального судьи (РАССЛЕДОВАТЬ)
rus_verbs:ВОЗОБНОВИТЬСЯ{}, // В Кемеровской области возобновилось движение по трассам международного значения (ВОЗОБНОВИТЬСЯ)
rus_verbs:ИЗМЕНИТЬСЯ{}, // изменилась она во всем (ИЗМЕНИТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // за широким окном комнаты город сверкал во тьме разноцветными огнями (СВЕРКАТЬ)
rus_verbs:СКОНЧАТЬСЯ{}, // В Риме скончался режиссёр знаменитого сериала «Спрут» (СКОНЧАТЬСЯ)
rus_verbs:ПРЯТАТЬСЯ{}, // Cкрытые спутники прячутся в кольцах Сатурна (ПРЯТАТЬСЯ)
rus_verbs:ВЫЗЫВАТЬ{}, // этот человек всегда вызывал во мне восхищение (ВЫЗЫВАТЬ)
rus_verbs:ВЫПУСТИТЬ{}, // Избирательные бюллетени могут выпустить в форме брошюры (ВЫПУСТИТЬ)
rus_verbs:НАЧИНАТЬСЯ{}, // В Москве начинается «марш в защиту детей» (НАЧИНАТЬСЯ)
rus_verbs:ЗАСТРЕЛИТЬ{}, // В Дагестане застрелили преподавателя медресе (ЗАСТРЕЛИТЬ)
rus_verbs:УРАВНЯТЬ{}, // Госзаказчиков уравняют в правах с поставщиками (УРАВНЯТЬ)
rus_verbs:промахнуться{}, // в первой половине невероятным образом промахнулся экс-форвард московского ЦСКА
rus_verbs:ОБЫГРАТЬ{}, // "Рубин" сенсационно обыграл в Мадриде вторую команду Испании (ОБЫГРАТЬ)
rus_verbs:ВКЛЮЧИТЬ{}, // В Челябинской области включен аварийный роуминг (ВКЛЮЧИТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В селах Балаковского района участились случаи поджогов стогов сена (УЧАСТИТЬСЯ)
rus_verbs:СПАСТИ{}, // В Австралии спасли повисшего на проводе коршуна (СПАСТИ)
rus_verbs:ВЫПАСТЬ{}, // Отдельные фрагменты достигли земли, выпав в виде метеоритного дождя (ВЫПАСТЬ)
rus_verbs:НАГРАДИТЬ{}, // В Лондоне наградили лауреатов премии Brit Awards (НАГРАДИТЬ)
rus_verbs:ОТКРЫТЬСЯ{}, // в Москве открылся первый международный кинофестиваль
rus_verbs:ПОДНИМАТЬСЯ{}, // во мне поднималось раздражение
rus_verbs:ЗАВЕРШИТЬСЯ{}, // В Италии завершился традиционный Венецианский карнавал (ЗАВЕРШИТЬСЯ)
инфинитив:проводить{ вид:несоверш }, // Кузбасские депутаты проводят в Кемерове прием граждан
глагол:проводить{ вид:несоверш },
деепричастие:проводя{},
rus_verbs:отсутствовать{}, // Хозяйка квартиры в этот момент отсутствовала
rus_verbs:доложить{}, // об итогах своего визита он намерен доложить в американском сенате и Белом доме (ДОЛОЖИТЬ ОБ, В предл)
rus_verbs:ИЗДЕВАТЬСЯ{}, // В Эйлате издеваются над туристами (ИЗДЕВАТЬСЯ В предл)
rus_verbs:НАРУШИТЬ{}, // В нескольких регионах нарушено наземное транспортное сообщение (НАРУШИТЬ В предл)
rus_verbs:БЕЖАТЬ{}, // далеко внизу во тьме бежала невидимая река (БЕЖАТЬ В предл)
rus_verbs:СОБРАТЬСЯ{}, // Дмитрий оглядел собравшихся во дворе мальчишек (СОБРАТЬСЯ В предл)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // далеко вверху во тьме послышался ответ (ПОСЛЫШАТЬСЯ В предл)
rus_verbs:ПОКАЗАТЬСЯ{}, // во дворе показалась высокая фигура (ПОКАЗАТЬСЯ В предл)
rus_verbs:УЛЫБНУТЬСЯ{}, // Дмитрий горько улыбнулся во тьме (УЛЫБНУТЬСЯ В предл)
rus_verbs:ТЯНУТЬСЯ{}, // убежища тянулись во всех направлениях (ТЯНУТЬСЯ В предл)
rus_verbs:РАНИТЬ{}, // В американском университете ранили человека (РАНИТЬ В предл)
rus_verbs:ЗАХВАТИТЬ{}, // Пираты освободили корабль, захваченный в Гвинейском заливе (ЗАХВАТИТЬ В предл)
rus_verbs:РАЗБЕГАТЬСЯ{}, // люди разбегались во всех направлениях (РАЗБЕГАТЬСЯ В предл)
rus_verbs:ПОГАСНУТЬ{}, // во всем доме погас свет (ПОГАСНУТЬ В предл)
rus_verbs:ПОШЕВЕЛИТЬСЯ{}, // Дмитрий пошевелился во сне (ПОШЕВЕЛИТЬСЯ В предл)
rus_verbs:ЗАСТОНАТЬ{}, // раненый застонал во сне (ЗАСТОНАТЬ В предл)
прилагательное:ВИНОВАТЫЙ{}, // во всем виновато вино (ВИНОВАТЫЙ В)
rus_verbs:ОСТАВЛЯТЬ{}, // США оставляют в районе Персидского залива только один авианосец (ОСТАВЛЯТЬ В предл)
rus_verbs:ОТКАЗЫВАТЬСЯ{}, // В России отказываются от планов авиагруппы в Арктике (ОТКАЗЫВАТЬСЯ В предл)
rus_verbs:ЛИКВИДИРОВАТЬ{}, // В Кабардино-Балкарии ликвидирован подпольный завод по переработке нефти (ЛИКВИДИРОВАТЬ В предл)
rus_verbs:РАЗОБЛАЧИТЬ{}, // В США разоблачили крупнейшую махинацию с кредитками (РАЗОБЛАЧИТЬ В предл)
rus_verbs:СХВАТИТЬ{}, // их схватили во сне (СХВАТИТЬ В предл)
rus_verbs:НАЧАТЬ{}, // В Белгороде начали сбор подписей за отставку мэра (НАЧАТЬ В предл)
rus_verbs:РАСТИ{}, // Cамая маленькая муха растёт в голове муравья (РАСТИ В предл)
rus_verbs:похитить{}, // Двое россиян, похищенных террористами в Сирии, освобождены (похитить в предл)
rus_verbs:УЧАСТВОВАТЬ{}, // были застрелены два испанских гражданских гвардейца , участвовавших в слежке (УЧАСТВОВАТЬ В)
rus_verbs:УСЫНОВИТЬ{}, // Американцы забирают усыновленных в России детей (УСЫНОВИТЬ В)
rus_verbs:ПРОИЗВЕСТИ{}, // вы не увидите мясо или молоко , произведенное в районе (ПРОИЗВЕСТИ В предл)
rus_verbs:ОРИЕНТИРОВАТЬСЯ{}, // призван помочь госслужащему правильно ориентироваться в сложных нравственных коллизиях (ОРИЕНТИРОВАТЬСЯ В)
rus_verbs:ПОВРЕДИТЬ{}, // В зале игровых автоматов повреждены стены и потолок (ПОВРЕДИТЬ В предл)
rus_verbs:ИЗЪЯТЬ{}, // В настоящее время в детском учреждении изъяты суточные пробы пищи (ИЗЪЯТЬ В предл)
rus_verbs:СОДЕРЖАТЬСЯ{}, // осужденных , содержащихся в помещениях штрафного изолятора (СОДЕРЖАТЬСЯ В)
rus_verbs:ОТЧИСЛИТЬ{}, // был отчислен за неуспеваемость в 2007 году (ОТЧИСЛИТЬ В предл)
rus_verbs:проходить{}, // находился на санкционированном митинге , проходившем в рамках празднования Дня народного единства (проходить в предл)
rus_verbs:ПОДУМЫВАТЬ{}, // сейчас в правительстве Приамурья подумывают о создании специального пункта помощи туристам (ПОДУМЫВАТЬ В)
rus_verbs:ОТРАПОРТОВЫВАТЬ{}, // главы субъектов не просто отрапортовывали в Москве (ОТРАПОРТОВЫВАТЬ В предл)
rus_verbs:ВЕСТИСЬ{}, // в городе ведутся работы по установке праздничной иллюминации (ВЕСТИСЬ В)
rus_verbs:ОДОБРИТЬ{}, // Одобренным в первом чтении законопроектом (ОДОБРИТЬ В)
rus_verbs:ЗАМЫЛИТЬСЯ{}, // ему легче исправлять , то , что замылилось в глазах предыдущего руководства (ЗАМЫЛИТЬСЯ В)
rus_verbs:АВТОРИЗОВАТЬСЯ{}, // потом имеют право авторизоваться в системе Международного бакалавриата (АВТОРИЗОВАТЬСЯ В)
rus_verbs:ОПУСТИТЬСЯ{}, // Россия опустилась в списке на шесть позиций (ОПУСТИТЬСЯ В предл)
rus_verbs:СГОРЕТЬ{}, // Совладелец сгоревшего в Бразилии ночного клуба сдался полиции (СГОРЕТЬ В)
частица:нет{}, // В этом нет сомнения.
частица:нету{}, // В этом нету сомнения.
rus_verbs:поджечь{}, // Поджегший себя в Москве мужчина оказался ветераном-афганцем
rus_verbs:ввести{}, // В Молдавии введен запрет на амнистию или помилование педофилов.
прилагательное:ДОСТУПНЫЙ{}, // Наиболее интересные таблички доступны в основной экспозиции музея (ДОСТУПНЫЙ В)
rus_verbs:ПОВИСНУТЬ{}, // вопрос повис в мглистом демократическом воздухе (ПОВИСНУТЬ В)
rus_verbs:ВЗОРВАТЬ{}, // В Ираке смертник взорвал в мечети группу туркменов (ВЗОРВАТЬ В)
rus_verbs:ОТНЯТЬ{}, // В Финляндии у россиянки, прибывшей по туристической визе, отняли детей (ОТНЯТЬ В)
rus_verbs:НАЙТИ{}, // Я недавно посетил врача и у меня в глазах нашли какую-то фигню (НАЙТИ В предл)
rus_verbs:ЗАСТРЕЛИТЬСЯ{}, // Девушка, застрелившаяся в центре Киева, была замешана в скандале с влиятельными людьми (ЗАСТРЕЛИТЬСЯ В)
rus_verbs:стартовать{}, // В Страсбурге сегодня стартует зимняя сессия Парламентской ассамблеи Совета Европы (стартовать в)
rus_verbs:ЗАКЛАДЫВАТЬСЯ{}, // Отношение к деньгам закладывается в детстве (ЗАКЛАДЫВАТЬСЯ В)
rus_verbs:НАПИВАТЬСЯ{}, // Депутатам помешают напиваться в здании Госдумы (НАПИВАТЬСЯ В)
rus_verbs:ВЫПРАВИТЬСЯ{}, // Прежде всего было заявлено, что мировая экономика каким-то образом сама выправится в процессе бизнес-цикла (ВЫПРАВИТЬСЯ В)
rus_verbs:ЯВЛЯТЬСЯ{}, // она являлась ко мне во всех моих снах (ЯВЛЯТЬСЯ В)
rus_verbs:СТАЖИРОВАТЬСЯ{}, // сейчас я стажируюсь в одной компании (СТАЖИРОВАТЬСЯ В)
rus_verbs:ОБСТРЕЛЯТЬ{}, // Уроженцы Чечни, обстрелявшие полицейских в центре Москвы, арестованы (ОБСТРЕЛЯТЬ В)
rus_verbs:РАСПРОСТРАНИТЬ{}, // Воски — распространённые в растительном и животном мире сложные эфиры высших жирных кислот и высших высокомолекулярных спиртов (РАСПРОСТРАНИТЬ В)
rus_verbs:ПРИВЕСТИ{}, // Сравнительная фугасность некоторых взрывчатых веществ приведена в следующей таблице (ПРИВЕСТИ В)
rus_verbs:ЗАПОДОЗРИТЬ{}, // Чиновников Минкультуры заподозрили в афере с заповедными землями (ЗАПОДОЗРИТЬ В)
rus_verbs:НАСТУПАТЬ{}, // В Гренландии стали наступать ледники (НАСТУПАТЬ В)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // В истории Земли выделяются следующие ледниковые эры (ВЫДЕЛЯТЬСЯ В)
rus_verbs:ПРЕДСТАВИТЬ{}, // Данные представлены в хронологическом порядке (ПРЕДСТАВИТЬ В)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:ПОДАВАТЬ{}, // Готовые компоты подают в столовых и кафе (ПОДАВАТЬ В)
rus_verbs:ГОТОВИТЬ{}, // Сегодня компот готовят в домашних условиях из сухофруктов или замороженных фруктов и ягод (ГОТОВИТЬ В)
rus_verbs:ВОЗДЕЛЫВАТЬСЯ{}, // в настоящее время он повсеместно возделывается в огородах (ВОЗДЕЛЫВАТЬСЯ В)
rus_verbs:РАСКЛАДЫВАТЬ{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:РАСКЛАДЫВАТЬСЯ{},
rus_verbs:СОБИРАТЬСЯ{}, // Обыкновенно огурцы собираются в полуспелом состоянии (СОБИРАТЬСЯ В)
rus_verbs:ПРОГРЕМЕТЬ{}, // В торговом центре Ижевска прогремел взрыв (ПРОГРЕМЕТЬ В)
rus_verbs:СНЯТЬ{}, // чтобы снять их во всей красоте. (СНЯТЬ В)
rus_verbs:ЯВИТЬСЯ{}, // она явилась к нему во сне. (ЯВИТЬСЯ В)
rus_verbs:ВЕРИТЬ{}, // мы же во всем верили капитану. (ВЕРИТЬ В предл)
rus_verbs:выдержать{}, // Игра выдержана в научно-фантастическом стиле. (ВЫДЕРЖАННЫЙ В)
rus_verbs:ПРЕОДОЛЕТЬ{}, // мы пытались преодолеть ее во многих местах. (ПРЕОДОЛЕТЬ В)
инфинитив:НАПИСАТЬ{ aux stress="напис^ать" }, // Программа, написанная в спешке, выполнила недопустимую операцию. (НАПИСАТЬ В)
глагол:НАПИСАТЬ{ aux stress="напис^ать" },
прилагательное:НАПИСАННЫЙ{},
rus_verbs:ЕСТЬ{}, // ты даже во сне ел. (ЕСТЬ/кушать В)
rus_verbs:УСЕСТЬСЯ{}, // Он удобно уселся в кресле. (УСЕСТЬСЯ В)
rus_verbs:ТОРГОВАТЬ{}, // Он торгует в палатке. (ТОРГОВАТЬ В)
rus_verbs:СОВМЕСТИТЬ{}, // Он совместил в себе писателя и художника. (СОВМЕСТИТЬ В)
rus_verbs:ЗАБЫВАТЬ{}, // об этом нельзя забывать даже во сне. (ЗАБЫВАТЬ В)
rus_verbs:поговорить{}, // Давайте поговорим об этом в присутствии адвоката
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
rus_verbs:раскрыть{}, // В России раскрыли крупнейшую в стране сеть фальшивомонетчиков (РАСКРЫТЬ В)
rus_verbs:соединить{}, // соединить в себе (СОЕДИНИТЬ В предл)
rus_verbs:избрать{}, // В Южной Корее избран новый президент (ИЗБРАТЬ В предл)
rus_verbs:проводиться{}, // Обыски проводятся в воронежском Доме прав человека (ПРОВОДИТЬСЯ В)
безлич_глагол:хватает{}, // В этой статье не хватает ссылок на источники информации. (БЕЗЛИЧ хватать в)
rus_verbs:наносить{}, // В ближнем бою наносит мощные удары своим костлявым кулаком. (НАНОСИТЬ В + предл.)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
прилагательное:известный{}, // В Европе сахар был известен ещё римлянам. (ИЗВЕСТНЫЙ В)
rus_verbs:выработать{}, // Способы, выработанные во Франции, перешли затем в Германию и другие страны Европы. (ВЫРАБОТАТЬ В)
rus_verbs:КУЛЬТИВИРОВАТЬСЯ{}, // Культивируется в регионах с умеренным климатом с умеренным количеством осадков и требует плодородной почвы. (КУЛЬТИВИРОВАТЬСЯ В)
rus_verbs:чаять{}, // мама души не чаяла в своих детях (ЧАЯТЬ В)
rus_verbs:улыбаться{}, // Вадим улыбался во сне. (УЛЫБАТЬСЯ В)
rus_verbs:растеряться{}, // Приезжие растерялись в бетонном лабиринте улиц (РАСТЕРЯТЬСЯ В)
rus_verbs:выть{}, // выли волки где-то в лесу (ВЫТЬ В)
rus_verbs:ЗАВЕРИТЬ{}, // выступавший заверил нас в намерении выполнить обещание (ЗАВЕРИТЬ В)
rus_verbs:ИСЧЕЗНУТЬ{}, // звери исчезли во мраке. (ИСЧЕЗНУТЬ В)
rus_verbs:ВСТАТЬ{}, // встать во главе человечества. (ВСТАТЬ В)
rus_verbs:УПОТРЕБЛЯТЬ{}, // В Тибете употребляют кирпичный зелёный чай. (УПОТРЕБЛЯТЬ В)
rus_verbs:ПОДАВАТЬСЯ{}, // Напиток охлаждается и подаётся в холодном виде. (ПОДАВАТЬСЯ В)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // в игре используются текстуры большего разрешения (ИСПОЛЬЗОВАТЬСЯ В)
rus_verbs:объявить{}, // В газете объявили о конкурсе.
rus_verbs:ВСПЫХНУТЬ{}, // во мне вспыхнул гнев. (ВСПЫХНУТЬ В)
rus_verbs:КРЫТЬСЯ{}, // В его словах кроется угроза. (КРЫТЬСЯ В)
rus_verbs:подняться{}, // В классе вдруг поднялся шум. (подняться в)
rus_verbs:наступить{}, // В классе наступила полная тишина. (наступить в)
rus_verbs:кипеть{}, // В нём кипит злоба. (кипеть в)
rus_verbs:соединиться{}, // В нём соединились храбрость и великодушие. (соединиться в)
инфинитив:ПАРИТЬ{ aux stress="пар^ить"}, // Высоко в небе парит орёл, плавно описывая круги. (ПАРИТЬ В)
глагол:ПАРИТЬ{ aux stress="пар^ить"},
деепричастие:паря{ aux stress="пар^я" },
прилагательное:ПАРЯЩИЙ{},
прилагательное:ПАРИВШИЙ{},
rus_verbs:СИЯТЬ{}, // Главы собора сияли в лучах солнца. (СИЯТЬ В)
rus_verbs:РАСПОЛОЖИТЬ{}, // Гостиница расположена глубоко в горах. (РАСПОЛОЖИТЬ В)
rus_verbs:развиваться{}, // Действие в комедии развивается в двух планах. (развиваться в)
rus_verbs:ПОСАДИТЬ{}, // Дети посадили у нас во дворе цветы. (ПОСАДИТЬ В)
rus_verbs:ИСКОРЕНЯТЬ{}, // Дурные привычки следует искоренять в самом начале. (ИСКОРЕНЯТЬ В)
rus_verbs:ВОССТАНОВИТЬ{}, // Его восстановили в правах. (ВОССТАНОВИТЬ В)
rus_verbs:ПОЛАГАТЬСЯ{}, // мы полагаемся на него в этих вопросах (ПОЛАГАТЬСЯ В)
rus_verbs:УМИРАТЬ{}, // они умирали во сне. (УМИРАТЬ В)
rus_verbs:ПРИБАВИТЬ{}, // Она сильно прибавила в весе. (ПРИБАВИТЬ В)
rus_verbs:посмотреть{}, // Посмотрите в списке. (посмотреть в)
rus_verbs:производиться{}, // Выдача новых паспортов будет производиться в следующем порядке (производиться в)
rus_verbs:принять{}, // Документ принят в следующей редакции (принять в)
rus_verbs:сверкнуть{}, // меч его сверкнул во тьме. (сверкнуть в)
rus_verbs:ВЫРАБАТЫВАТЬ{}, // ты должен вырабатывать в себе силу воли (ВЫРАБАТЫВАТЬ В)
rus_verbs:достать{}, // Эти сведения мы достали в Волгограде. (достать в)
rus_verbs:звучать{}, // в доме звучала музыка (звучать в)
rus_verbs:колебаться{}, // колеблется в выборе (колебаться в)
rus_verbs:мешать{}, // мешать в кастрюле суп (мешать в)
rus_verbs:нарастать{}, // во мне нарастал гнев (нарастать в)
rus_verbs:отбыть{}, // Вадим отбыл в неизвестном направлении (отбыть в)
rus_verbs:светиться{}, // во всем доме светилось только окно ее спальни. (светиться в)
rus_verbs:вычитывать{}, // вычитывать в книге
rus_verbs:гудеть{}, // У него в ушах гудит.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:поблескивать{}, // Красивое стеклышко поблескивало в пыльной траве у дорожки.
rus_verbs:разойтись{}, // Они разошлись в темноте.
rus_verbs:прибежать{}, // Мальчик прибежал в слезах.
rus_verbs:биться{}, // Она билась в истерике.
rus_verbs:регистрироваться{}, // регистрироваться в системе
rus_verbs:считать{}, // я буду считать в уме
rus_verbs:трахаться{}, // трахаться в гамаке
rus_verbs:сконцентрироваться{}, // сконцентрироваться в одной точке
rus_verbs:разрушать{}, // разрушать в дробилке
rus_verbs:засидеться{}, // засидеться в гостях
rus_verbs:засиживаться{}, // засиживаться в гостях
rus_verbs:утопить{}, // утопить лодку в реке (утопить в реке)
rus_verbs:навестить{}, // навестить в доме престарелых
rus_verbs:запомнить{}, // запомнить в кэше
rus_verbs:убивать{}, // убивать в помещении полиции (-score убивать неодуш. дом.)
rus_verbs:базироваться{}, // установка базируется в черте города (ngram черта города - проверить что есть проверка)
rus_verbs:покупать{}, // Чаще всего россияне покупают в интернете бытовую технику.
rus_verbs:ходить{}, // ходить в пальто (сделать ХОДИТЬ + в + ОДЕЖДА предл.п.)
rus_verbs:заложить{}, // диверсанты заложили в помещении бомбу
rus_verbs:оглядываться{}, // оглядываться в зеркале
rus_verbs:нарисовать{}, // нарисовать в тетрадке
rus_verbs:пробить{}, // пробить отверствие в стене
rus_verbs:повертеть{}, // повертеть в руке
rus_verbs:вертеть{}, // Я вертел в руках
rus_verbs:рваться{}, // Веревка рвется в месте надреза
rus_verbs:распространяться{}, // распространяться в среде наркоманов
rus_verbs:попрощаться{}, // попрощаться в здании морга
rus_verbs:соображать{}, // соображать в уме
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш }, // просыпаться в чужой кровати
rus_verbs:заехать{}, // Коля заехал в гости (в гости - устойчивый наречный оборот)
rus_verbs:разобрать{}, // разобрать в гараже
rus_verbs:помереть{}, // помереть в пути
rus_verbs:различить{}, // различить в темноте
rus_verbs:рисовать{}, // рисовать в графическом редакторе
rus_verbs:проследить{}, // проследить в записях камер слежения
rus_verbs:совершаться{}, // Правосудие совершается в суде
rus_verbs:задремать{}, // задремать в кровати
rus_verbs:ругаться{}, // ругаться в комнате
rus_verbs:зазвучать{}, // зазвучать в радиоприемниках
rus_verbs:задохнуться{}, // задохнуться в воде
rus_verbs:порождать{}, // порождать в неокрепших умах
rus_verbs:отдыхать{}, // отдыхать в санатории
rus_verbs:упоминаться{}, // упоминаться в предыдущем сообщении
rus_verbs:образовать{}, // образовать в пробирке темную взвесь
rus_verbs:отмечать{}, // отмечать в списке
rus_verbs:подчеркнуть{}, // подчеркнуть в блокноте
rus_verbs:плясать{}, // плясать в откружении незнакомых людей
rus_verbs:повысить{}, // повысить в звании
rus_verbs:поджидать{}, // поджидать в подъезде
rus_verbs:отказать{}, // отказать в пересмотре дела
rus_verbs:раствориться{}, // раствориться в бензине
rus_verbs:отражать{}, // отражать в стихах
rus_verbs:дремать{}, // дремать в гамаке
rus_verbs:применяться{}, // применяться в домашних условиях
rus_verbs:присниться{}, // присниться во сне
rus_verbs:трястись{}, // трястись в драндулете
rus_verbs:сохранять{}, // сохранять в неприкосновенности
rus_verbs:расстрелять{}, // расстрелять в ложбине
rus_verbs:рассчитать{}, // рассчитать в программе
rus_verbs:перебирать{}, // перебирать в руке
rus_verbs:разбиться{}, // разбиться в аварии
rus_verbs:поискать{}, // поискать в углу
rus_verbs:мучиться{}, // мучиться в тесной клетке
rus_verbs:замелькать{}, // замелькать в телевизоре
rus_verbs:грустить{}, // грустить в одиночестве
rus_verbs:крутить{}, // крутить в банке
rus_verbs:объявиться{}, // объявиться в городе
rus_verbs:подготовить{}, // подготовить в тайне
rus_verbs:различать{}, // различать в смеси
rus_verbs:обнаруживать{}, // обнаруживать в крови
rus_verbs:киснуть{}, // киснуть в захолустье
rus_verbs:оборваться{}, // оборваться в начале фразы
rus_verbs:запутаться{}, // запутаться в веревках
rus_verbs:общаться{}, // общаться в интимной обстановке
rus_verbs:сочинить{}, // сочинить в ресторане
rus_verbs:изобрести{}, // изобрести в домашней лаборатории
rus_verbs:прокомментировать{}, // прокомментировать в своем блоге
rus_verbs:давить{}, // давить в зародыше
rus_verbs:повториться{}, // повториться в новом обличье
rus_verbs:отставать{}, // отставать в общем зачете
rus_verbs:разработать{}, // разработать в лаборатории
rus_verbs:качать{}, // качать в кроватке
rus_verbs:заменить{}, // заменить в двигателе
rus_verbs:задыхаться{}, // задыхаться в душной и влажной атмосфере
rus_verbs:забегать{}, // забегать в спешке
rus_verbs:наделать{}, // наделать в решении ошибок
rus_verbs:исказиться{}, // исказиться в кривом зеркале
rus_verbs:тушить{}, // тушить в помещении пожар
rus_verbs:охранять{}, // охранять в здании входы
rus_verbs:приметить{}, // приметить в кустах
rus_verbs:скрыть{}, // скрыть в складках одежды
rus_verbs:удерживать{}, // удерживать в заложниках
rus_verbs:увеличиваться{}, // увеличиваться в размере
rus_verbs:красоваться{}, // красоваться в новом платье
rus_verbs:сохраниться{}, // сохраниться в тепле
rus_verbs:лечить{}, // лечить в стационаре
rus_verbs:смешаться{}, // смешаться в баке
rus_verbs:прокатиться{}, // прокатиться в троллейбусе
rus_verbs:договариваться{}, // договариваться в закрытом кабинете
rus_verbs:опубликовать{}, // опубликовать в официальном блоге
rus_verbs:охотиться{}, // охотиться в прериях
rus_verbs:отражаться{}, // отражаться в окне
rus_verbs:понизить{}, // понизить в должности
rus_verbs:обедать{}, // обедать в ресторане
rus_verbs:посидеть{}, // посидеть в тени
rus_verbs:сообщаться{}, // сообщаться в оппозиционной газете
rus_verbs:свершиться{}, // свершиться в суде
rus_verbs:ночевать{}, // ночевать в гостинице
rus_verbs:темнеть{}, // темнеть в воде
rus_verbs:гибнуть{}, // гибнуть в застенках
rus_verbs:усиливаться{}, // усиливаться в направлении главного удара
rus_verbs:расплыться{}, // расплыться в улыбке
rus_verbs:превышать{}, // превышать в несколько раз
rus_verbs:проживать{}, // проживать в отдельной коморке
rus_verbs:голубеть{}, // голубеть в тепле
rus_verbs:исследовать{}, // исследовать в естественных условиях
rus_verbs:обитать{}, // обитать в лесу
rus_verbs:скучать{}, // скучать в одиночестве
rus_verbs:сталкиваться{}, // сталкиваться в воздухе
rus_verbs:таиться{}, // таиться в глубине
rus_verbs:спасать{}, // спасать в море
rus_verbs:заблудиться{}, // заблудиться в лесу
rus_verbs:создаться{}, // создаться в новом виде
rus_verbs:пошарить{}, // пошарить в кармане
rus_verbs:планировать{}, // планировать в программе
rus_verbs:отбить{}, // отбить в нижней части
rus_verbs:отрицать{}, // отрицать в суде свою вину
rus_verbs:основать{}, // основать в пустыне новый город
rus_verbs:двоить{}, // двоить в глазах
rus_verbs:устоять{}, // устоять в лодке
rus_verbs:унять{}, // унять в ногах дрожь
rus_verbs:отзываться{}, // отзываться в обзоре
rus_verbs:притормозить{}, // притормозить в траве
rus_verbs:читаться{}, // читаться в глазах
rus_verbs:житься{}, // житься в деревне
rus_verbs:заиграть{}, // заиграть в жилах
rus_verbs:шевелить{}, // шевелить в воде
rus_verbs:зазвенеть{}, // зазвенеть в ушах
rus_verbs:зависнуть{}, // зависнуть в библиотеке
rus_verbs:затаить{}, // затаить в душе обиду
rus_verbs:сознаться{}, // сознаться в совершении
rus_verbs:протекать{}, // протекать в легкой форме
rus_verbs:выясняться{}, // выясняться в ходе эксперимента
rus_verbs:скрестить{}, // скрестить в неволе
rus_verbs:наводить{}, // наводить в комнате порядок
rus_verbs:значиться{}, // значиться в документах
rus_verbs:заинтересовать{}, // заинтересовать в получении результатов
rus_verbs:познакомить{}, // познакомить в непринужденной обстановке
rus_verbs:рассеяться{}, // рассеяться в воздухе
rus_verbs:грохнуть{}, // грохнуть в подвале
rus_verbs:обвинять{}, // обвинять в вымогательстве
rus_verbs:столпиться{}, // столпиться в фойе
rus_verbs:порыться{}, // порыться в сумке
rus_verbs:ослабить{}, // ослабить в верхней части
rus_verbs:обнаруживаться{}, // обнаруживаться в кармане куртки
rus_verbs:спастись{}, // спастись в хижине
rus_verbs:прерваться{}, // прерваться в середине фразы
rus_verbs:применять{}, // применять в повседневной работе
rus_verbs:строиться{}, // строиться в зоне отчуждения
rus_verbs:путешествовать{}, // путешествовать в самолете
rus_verbs:побеждать{}, // побеждать в честной битве
rus_verbs:погубить{}, // погубить в себе артиста
rus_verbs:рассматриваться{}, // рассматриваться в следующей главе
rus_verbs:продаваться{}, // продаваться в специализированном магазине
rus_verbs:разместиться{}, // разместиться в аудитории
rus_verbs:повидать{}, // повидать в жизни
rus_verbs:настигнуть{}, // настигнуть в пригородах
rus_verbs:сгрудиться{}, // сгрудиться в центре загона
rus_verbs:укрыться{}, // укрыться в доме
rus_verbs:расплакаться{}, // расплакаться в суде
rus_verbs:пролежать{}, // пролежать в канаве
rus_verbs:замерзнуть{}, // замерзнуть в ледяной воде
rus_verbs:поскользнуться{}, // поскользнуться в коридоре
rus_verbs:таскать{}, // таскать в руках
rus_verbs:нападать{}, // нападать в вольере
rus_verbs:просматривать{}, // просматривать в браузере
rus_verbs:обдумать{}, // обдумать в дороге
rus_verbs:обвинить{}, // обвинить в измене
rus_verbs:останавливать{}, // останавливать в дверях
rus_verbs:теряться{}, // теряться в догадках
rus_verbs:погибать{}, // погибать в бою
rus_verbs:обозначать{}, // обозначать в списке
rus_verbs:запрещать{}, // запрещать в парке
rus_verbs:долететь{}, // долететь в вертолёте
rus_verbs:тесниться{}, // тесниться в каморке
rus_verbs:уменьшаться{}, // уменьшаться в размере
rus_verbs:издавать{}, // издавать в небольшом издательстве
rus_verbs:хоронить{}, // хоронить в море
rus_verbs:перемениться{}, // перемениться в лице
rus_verbs:установиться{}, // установиться в северных областях
rus_verbs:прикидывать{}, // прикидывать в уме
rus_verbs:затаиться{}, // затаиться в траве
rus_verbs:раздобыть{}, // раздобыть в аптеке
rus_verbs:перебросить{}, // перебросить в товарном составе
rus_verbs:погружаться{}, // погружаться в батискафе
rus_verbs:поживать{}, // поживать в одиночестве
rus_verbs:признаваться{}, // признаваться в любви
rus_verbs:захватывать{}, // захватывать в здании
rus_verbs:покачиваться{}, // покачиваться в лодке
rus_verbs:крутиться{}, // крутиться в колесе
rus_verbs:помещаться{}, // помещаться в ящике
rus_verbs:питаться{}, // питаться в столовой
rus_verbs:отдохнуть{}, // отдохнуть в пансионате
rus_verbs:кататься{}, // кататься в коляске
rus_verbs:поработать{}, // поработать в цеху
rus_verbs:подразумевать{}, // подразумевать в задании
rus_verbs:ограбить{}, // ограбить в подворотне
rus_verbs:преуспеть{}, // преуспеть в бизнесе
rus_verbs:заерзать{}, // заерзать в кресле
rus_verbs:разъяснить{}, // разъяснить в другой статье
rus_verbs:продвинуться{}, // продвинуться в изучении
rus_verbs:поколебаться{}, // поколебаться в начале
rus_verbs:засомневаться{}, // засомневаться в честности
rus_verbs:приникнуть{}, // приникнуть в уме
rus_verbs:скривить{}, // скривить в усмешке
rus_verbs:рассечь{}, // рассечь в центре опухоли
rus_verbs:перепутать{}, // перепутать в роддоме
rus_verbs:посмеяться{}, // посмеяться в перерыве
rus_verbs:отмечаться{}, // отмечаться в полицейском участке
rus_verbs:накопиться{}, // накопиться в отстойнике
rus_verbs:уносить{}, // уносить в руках
rus_verbs:навещать{}, // навещать в больнице
rus_verbs:остыть{}, // остыть в проточной воде
rus_verbs:запереться{}, // запереться в комнате
rus_verbs:обогнать{}, // обогнать в первом круге
rus_verbs:убеждаться{}, // убеждаться в неизбежности
rus_verbs:подбирать{}, // подбирать в магазине
rus_verbs:уничтожать{}, // уничтожать в полете
rus_verbs:путаться{}, // путаться в показаниях
rus_verbs:притаиться{}, // притаиться в темноте
rus_verbs:проплывать{}, // проплывать в лодке
rus_verbs:засесть{}, // засесть в окопе
rus_verbs:подцепить{}, // подцепить в баре
rus_verbs:насчитать{}, // насчитать в диктанте несколько ошибок
rus_verbs:оправдаться{}, // оправдаться в суде
rus_verbs:созреть{}, // созреть в естественных условиях
rus_verbs:раскрываться{}, // раскрываться в подходящих условиях
rus_verbs:ожидаться{}, // ожидаться в верхней части
rus_verbs:одеваться{}, // одеваться в дорогих бутиках
rus_verbs:упрекнуть{}, // упрекнуть в недостатке опыта
rus_verbs:грабить{}, // грабить в подворотне
rus_verbs:ужинать{}, // ужинать в ресторане
rus_verbs:гонять{}, // гонять в жилах
rus_verbs:уверить{}, // уверить в безопасности
rus_verbs:потеряться{}, // потеряться в лесу
rus_verbs:устанавливаться{}, // устанавливаться в комнате
rus_verbs:предоставлять{}, // предоставлять в суде
rus_verbs:протянуться{}, // протянуться в стене
rus_verbs:допрашивать{}, // допрашивать в бункере
rus_verbs:проработать{}, // проработать в кабинете
rus_verbs:сосредоточить{}, // сосредоточить в своих руках
rus_verbs:утвердить{}, // утвердить в должности
rus_verbs:сочинять{}, // сочинять в дороге
rus_verbs:померкнуть{}, // померкнуть в глазах
rus_verbs:показываться{}, // показываться в окошке
rus_verbs:похудеть{}, // похудеть в талии
rus_verbs:проделывать{}, // проделывать в стене
rus_verbs:прославиться{}, // прославиться в интернете
rus_verbs:сдохнуть{}, // сдохнуть в нищете
rus_verbs:раскинуться{}, // раскинуться в степи
rus_verbs:развить{}, // развить в себе способности
rus_verbs:уставать{}, // уставать в цеху
rus_verbs:укрепить{}, // укрепить в земле
rus_verbs:числиться{}, // числиться в списке
rus_verbs:образовывать{}, // образовывать в смеси
rus_verbs:екнуть{}, // екнуть в груди
rus_verbs:одобрять{}, // одобрять в своей речи
rus_verbs:запить{}, // запить в одиночестве
rus_verbs:забыться{}, // забыться в тяжелом сне
rus_verbs:чернеть{}, // чернеть в кислой среде
rus_verbs:размещаться{}, // размещаться в гараже
rus_verbs:соорудить{}, // соорудить в гараже
rus_verbs:развивать{}, // развивать в себе
rus_verbs:пастись{}, // пастись в пойме
rus_verbs:формироваться{}, // формироваться в верхних слоях атмосферы
rus_verbs:ослабнуть{}, // ослабнуть в сочленении
rus_verbs:таить{}, // таить в себе
инфинитив:пробегать{ вид:несоверш }, глагол:пробегать{ вид:несоверш }, // пробегать в спешке
rus_verbs:приостановиться{}, // приостановиться в конце
rus_verbs:топтаться{}, // топтаться в грязи
rus_verbs:громить{}, // громить в финале
rus_verbs:заменять{}, // заменять в основном составе
rus_verbs:подъезжать{}, // подъезжать в колясках
rus_verbs:вычислить{}, // вычислить в уме
rus_verbs:заказывать{}, // заказывать в магазине
rus_verbs:осуществить{}, // осуществить в реальных условиях
rus_verbs:обосноваться{}, // обосноваться в дупле
rus_verbs:пытать{}, // пытать в камере
rus_verbs:поменять{}, // поменять в магазине
rus_verbs:совершиться{}, // совершиться в суде
rus_verbs:пролетать{}, // пролетать в вертолете
rus_verbs:сбыться{}, // сбыться во сне
rus_verbs:разговориться{}, // разговориться в отделении
rus_verbs:преподнести{}, // преподнести в красивой упаковке
rus_verbs:напечатать{}, // напечатать в типографии
rus_verbs:прорвать{}, // прорвать в центре
rus_verbs:раскачиваться{}, // раскачиваться в кресле
rus_verbs:задерживаться{}, // задерживаться в дверях
rus_verbs:угощать{}, // угощать в кафе
rus_verbs:проступать{}, // проступать в глубине
rus_verbs:шарить{}, // шарить в математике
rus_verbs:увеличивать{}, // увеличивать в конце
rus_verbs:расцвести{}, // расцвести в оранжерее
rus_verbs:закипеть{}, // закипеть в баке
rus_verbs:подлететь{}, // подлететь в вертолете
rus_verbs:рыться{}, // рыться в куче
rus_verbs:пожить{}, // пожить в гостинице
rus_verbs:добираться{}, // добираться в попутном транспорте
rus_verbs:перекрыть{}, // перекрыть в коридоре
rus_verbs:продержаться{}, // продержаться в барокамере
rus_verbs:разыскивать{}, // разыскивать в толпе
rus_verbs:освобождать{}, // освобождать в зале суда
rus_verbs:подметить{}, // подметить в человеке
rus_verbs:передвигаться{}, // передвигаться в узкой юбке
rus_verbs:продумать{}, // продумать в уме
rus_verbs:извиваться{}, // извиваться в траве
rus_verbs:процитировать{}, // процитировать в статье
rus_verbs:прогуливаться{}, // прогуливаться в парке
rus_verbs:защемить{}, // защемить в двери
rus_verbs:увеличиться{}, // увеличиться в объеме
rus_verbs:проявиться{}, // проявиться в результатах
rus_verbs:заскользить{}, // заскользить в ботинках
rus_verbs:пересказать{}, // пересказать в своем выступлении
rus_verbs:протестовать{}, // протестовать в здании парламента
rus_verbs:указываться{}, // указываться в путеводителе
rus_verbs:копошиться{}, // копошиться в песке
rus_verbs:проигнорировать{}, // проигнорировать в своей работе
rus_verbs:купаться{}, // купаться в речке
rus_verbs:подсчитать{}, // подсчитать в уме
rus_verbs:разволноваться{}, // разволноваться в классе
rus_verbs:придумывать{}, // придумывать в своем воображении
rus_verbs:предусмотреть{}, // предусмотреть в программе
rus_verbs:завертеться{}, // завертеться в колесе
rus_verbs:зачерпнуть{}, // зачерпнуть в ручье
rus_verbs:очистить{}, // очистить в химической лаборатории
rus_verbs:прозвенеть{}, // прозвенеть в коридорах
rus_verbs:уменьшиться{}, // уменьшиться в размере
rus_verbs:колыхаться{}, // колыхаться в проточной воде
rus_verbs:ознакомиться{}, // ознакомиться в автобусе
rus_verbs:ржать{}, // ржать в аудитории
rus_verbs:раскинуть{}, // раскинуть в микрорайоне
rus_verbs:разлиться{}, // разлиться в воде
rus_verbs:сквозить{}, // сквозить в словах
rus_verbs:задушить{}, // задушить в объятиях
rus_verbs:осудить{}, // осудить в особом порядке
rus_verbs:разгромить{}, // разгромить в честном поединке
rus_verbs:подслушать{}, // подслушать в кулуарах
rus_verbs:проповедовать{}, // проповедовать в сельских районах
rus_verbs:озарить{}, // озарить во сне
rus_verbs:потирать{}, // потирать в предвкушении
rus_verbs:описываться{}, // описываться в статье
rus_verbs:качаться{}, // качаться в кроватке
rus_verbs:усилить{}, // усилить в центре
rus_verbs:прохаживаться{}, // прохаживаться в новом костюме
rus_verbs:полечить{}, // полечить в больничке
rus_verbs:сниматься{}, // сниматься в римейке
rus_verbs:сыскать{}, // сыскать в наших краях
rus_verbs:поприветствовать{}, // поприветствовать в коридоре
rus_verbs:подтвердиться{}, // подтвердиться в эксперименте
rus_verbs:плескаться{}, // плескаться в теплой водичке
rus_verbs:расширяться{}, // расширяться в первом сегменте
rus_verbs:мерещиться{}, // мерещиться в тумане
rus_verbs:сгущаться{}, // сгущаться в воздухе
rus_verbs:храпеть{}, // храпеть во сне
rus_verbs:подержать{}, // подержать в руках
rus_verbs:накинуться{}, // накинуться в подворотне
rus_verbs:планироваться{}, // планироваться в закрытом режиме
rus_verbs:пробудить{}, // пробудить в себе
rus_verbs:побриться{}, // побриться в ванной
rus_verbs:сгинуть{}, // сгинуть в пучине
rus_verbs:окрестить{}, // окрестить в церкви
инфинитив:резюмировать{ вид:соверш }, глагол:резюмировать{ вид:соверш }, // резюмировать в конце выступления
rus_verbs:замкнуться{}, // замкнуться в себе
rus_verbs:прибавлять{}, // прибавлять в весе
rus_verbs:проплыть{}, // проплыть в лодке
rus_verbs:растворяться{}, // растворяться в тумане
rus_verbs:упрекать{}, // упрекать в небрежности
rus_verbs:затеряться{}, // затеряться в лабиринте
rus_verbs:перечитывать{}, // перечитывать в поезде
rus_verbs:перелететь{}, // перелететь в вертолете
rus_verbs:оживать{}, // оживать в теплой воде
rus_verbs:заглохнуть{}, // заглохнуть в полете
rus_verbs:кольнуть{}, // кольнуть в боку
rus_verbs:копаться{}, // копаться в куче
rus_verbs:развлекаться{}, // развлекаться в клубе
rus_verbs:отливать{}, // отливать в кустах
rus_verbs:зажить{}, // зажить в деревне
rus_verbs:одолжить{}, // одолжить в соседнем кабинете
rus_verbs:заклинать{}, // заклинать в своей речи
rus_verbs:различаться{}, // различаться в мелочах
rus_verbs:печататься{}, // печататься в типографии
rus_verbs:угадываться{}, // угадываться в контурах
rus_verbs:обрывать{}, // обрывать в начале
rus_verbs:поглаживать{}, // поглаживать в кармане
rus_verbs:подписывать{}, // подписывать в присутствии понятых
rus_verbs:добывать{}, // добывать в разломе
rus_verbs:скопиться{}, // скопиться в воротах
rus_verbs:повстречать{}, // повстречать в бане
rus_verbs:совпасть{}, // совпасть в упрощенном виде
rus_verbs:разрываться{}, // разрываться в точке спайки
rus_verbs:улавливать{}, // улавливать в датчике
rus_verbs:повстречаться{}, // повстречаться в лифте
rus_verbs:отразить{}, // отразить в отчете
rus_verbs:пояснять{}, // пояснять в примечаниях
rus_verbs:накормить{}, // накормить в столовке
rus_verbs:поужинать{}, // поужинать в ресторане
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть в суде
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить в молоке
rus_verbs:освоить{}, // освоить в работе
rus_verbs:зародиться{}, // зародиться в голове
rus_verbs:отплыть{}, // отплыть в старой лодке
rus_verbs:отстаивать{}, // отстаивать в суде
rus_verbs:осуждать{}, // осуждать в своем выступлении
rus_verbs:переговорить{}, // переговорить в перерыве
rus_verbs:разгораться{}, // разгораться в сердце
rus_verbs:укрыть{}, // укрыть в шалаше
rus_verbs:томиться{}, // томиться в застенках
rus_verbs:клубиться{}, // клубиться в воздухе
rus_verbs:сжигать{}, // сжигать в топке
rus_verbs:позавтракать{}, // позавтракать в кафешке
rus_verbs:функционировать{}, // функционировать в лабораторных условиях
rus_verbs:смять{}, // смять в руке
rus_verbs:разместить{}, // разместить в интернете
rus_verbs:пронести{}, // пронести в потайном кармане
rus_verbs:руководствоваться{}, // руководствоваться в работе
rus_verbs:нашарить{}, // нашарить в потемках
rus_verbs:закрутить{}, // закрутить в вихре
rus_verbs:просматриваться{}, // просматриваться в дальней перспективе
rus_verbs:распознать{}, // распознать в незнакомце
rus_verbs:повеситься{}, // повеситься в камере
rus_verbs:обшарить{}, // обшарить в поисках наркотиков
rus_verbs:наполняться{}, // наполняется в карьере
rus_verbs:засвистеть{}, // засвистеть в воздухе
rus_verbs:процветать{}, // процветать в мягком климате
rus_verbs:шуршать{}, // шуршать в простенке
rus_verbs:подхватывать{}, // подхватывать в полете
инфинитив:роиться{}, глагол:роиться{}, // роиться в воздухе
прилагательное:роившийся{}, прилагательное:роящийся{},
// деепричастие:роясь{ aux stress="ро^ясь" },
rus_verbs:преобладать{}, // преобладать в тексте
rus_verbs:посветлеть{}, // посветлеть в лице
rus_verbs:игнорировать{}, // игнорировать в рекомендациях
rus_verbs:обсуждаться{}, // обсуждаться в кулуарах
rus_verbs:отказывать{}, // отказывать в визе
rus_verbs:ощупывать{}, // ощупывать в кармане
rus_verbs:разливаться{}, // разливаться в цеху
rus_verbs:расписаться{}, // расписаться в получении
rus_verbs:учинить{}, // учинить в казарме
rus_verbs:плестись{}, // плестись в хвосте
rus_verbs:объявляться{}, // объявляться в группе
rus_verbs:повышаться{}, // повышаться в первой части
rus_verbs:напрягать{}, // напрягать в паху
rus_verbs:разрабатывать{}, // разрабатывать в студии
rus_verbs:хлопотать{}, // хлопотать в мэрии
rus_verbs:прерывать{}, // прерывать в самом начале
rus_verbs:каяться{}, // каяться в грехах
rus_verbs:освоиться{}, // освоиться в кабине
rus_verbs:подплыть{}, // подплыть в лодке
rus_verbs:замигать{}, // замигать в темноте
rus_verbs:оскорблять{}, // оскорблять в выступлении
rus_verbs:торжествовать{}, // торжествовать в душе
rus_verbs:поправлять{}, // поправлять в прологе
rus_verbs:угадывать{}, // угадывать в размытом изображении
rus_verbs:потоптаться{}, // потоптаться в прихожей
rus_verbs:переправиться{}, // переправиться в лодочке
rus_verbs:увериться{}, // увериться в невиновности
rus_verbs:забрезжить{}, // забрезжить в конце тоннеля
rus_verbs:утвердиться{}, // утвердиться во мнении
rus_verbs:завывать{}, // завывать в трубе
rus_verbs:заварить{}, // заварить в заварнике
rus_verbs:скомкать{}, // скомкать в руке
rus_verbs:перемещаться{}, // перемещаться в капсуле
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться в первом поле
rus_verbs:праздновать{}, // праздновать в баре
rus_verbs:мигать{}, // мигать в темноте
rus_verbs:обучить{}, // обучить в мастерской
rus_verbs:орудовать{}, // орудовать в кладовке
rus_verbs:упорствовать{}, // упорствовать в заблуждении
rus_verbs:переминаться{}, // переминаться в прихожей
rus_verbs:подрасти{}, // подрасти в теплице
rus_verbs:предписываться{}, // предписываться в законе
rus_verbs:приписать{}, // приписать в конце
rus_verbs:задаваться{}, // задаваться в своей статье
rus_verbs:чинить{}, // чинить в домашних условиях
rus_verbs:раздеваться{}, // раздеваться в пляжной кабинке
rus_verbs:пообедать{}, // пообедать в ресторанчике
rus_verbs:жрать{}, // жрать в чуланчике
rus_verbs:исполняться{}, // исполняться в антракте
rus_verbs:гнить{}, // гнить в тюрьме
rus_verbs:глодать{}, // глодать в конуре
rus_verbs:прослушать{}, // прослушать в дороге
rus_verbs:истратить{}, // истратить в кабаке
rus_verbs:стареть{}, // стареть в одиночестве
rus_verbs:разжечь{}, // разжечь в сердце
rus_verbs:совещаться{}, // совещаться в кабинете
rus_verbs:покачивать{}, // покачивать в кроватке
rus_verbs:отсидеть{}, // отсидеть в одиночке
rus_verbs:формировать{}, // формировать в умах
rus_verbs:захрапеть{}, // захрапеть во сне
rus_verbs:петься{}, // петься в хоре
rus_verbs:объехать{}, // объехать в автобусе
rus_verbs:поселить{}, // поселить в гостинице
rus_verbs:предаться{}, // предаться в книге
rus_verbs:заворочаться{}, // заворочаться во сне
rus_verbs:напрятать{}, // напрятать в карманах
rus_verbs:очухаться{}, // очухаться в незнакомом месте
rus_verbs:ограничивать{}, // ограничивать в движениях
rus_verbs:завертеть{}, // завертеть в руках
rus_verbs:печатать{}, // печатать в редакторе
rus_verbs:теплиться{}, // теплиться в сердце
rus_verbs:увязнуть{}, // увязнуть в зыбучем песке
rus_verbs:усмотреть{}, // усмотреть в обращении
rus_verbs:отыскаться{}, // отыскаться в запасах
rus_verbs:потушить{}, // потушить в горле огонь
rus_verbs:поубавиться{}, // поубавиться в размере
rus_verbs:зафиксировать{}, // зафиксировать в постоянной памяти
rus_verbs:смыть{}, // смыть в ванной
rus_verbs:заместить{}, // заместить в кресле
rus_verbs:угасать{}, // угасать в одиночестве
rus_verbs:сразить{}, // сразить в споре
rus_verbs:фигурировать{}, // фигурировать в бюллетене
rus_verbs:расплываться{}, // расплываться в глазах
rus_verbs:сосчитать{}, // сосчитать в уме
rus_verbs:сгуститься{}, // сгуститься в воздухе
rus_verbs:цитировать{}, // цитировать в своей статье
rus_verbs:помяться{}, // помяться в давке
rus_verbs:затрагивать{}, // затрагивать в процессе выполнения
rus_verbs:обтереть{}, // обтереть в гараже
rus_verbs:подстрелить{}, // подстрелить в пойме реки
rus_verbs:растереть{}, // растереть в руке
rus_verbs:подавлять{}, // подавлять в зародыше
rus_verbs:смешиваться{}, // смешиваться в чане
инфинитив:вычитать{ вид:соверш }, глагол:вычитать{ вид:соверш }, // вычитать в книжечке
rus_verbs:сократиться{}, // сократиться в обхвате
rus_verbs:занервничать{}, // занервничать в кабинете
rus_verbs:соприкоснуться{}, // соприкоснуться в полете
rus_verbs:обозначить{}, // обозначить в объявлении
rus_verbs:обучаться{}, // обучаться в училище
rus_verbs:снизиться{}, // снизиться в нижних слоях атмосферы
rus_verbs:лелеять{}, // лелеять в сердце
rus_verbs:поддерживаться{}, // поддерживаться в суде
rus_verbs:уплыть{}, // уплыть в лодочке
rus_verbs:резвиться{}, // резвиться в саду
rus_verbs:поерзать{}, // поерзать в гамаке
rus_verbs:оплатить{}, // оплатить в ресторане
rus_verbs:похвастаться{}, // похвастаться в компании
rus_verbs:знакомиться{}, // знакомиться в классе
rus_verbs:приплыть{}, // приплыть в подводной лодке
rus_verbs:зажигать{}, // зажигать в классе
rus_verbs:смыслить{}, // смыслить в математике
rus_verbs:закопать{}, // закопать в огороде
rus_verbs:порхать{}, // порхать в зарослях
rus_verbs:потонуть{}, // потонуть в бумажках
rus_verbs:стирать{}, // стирать в холодной воде
rus_verbs:подстерегать{}, // подстерегать в придорожных кустах
rus_verbs:погулять{}, // погулять в парке
rus_verbs:предвкушать{}, // предвкушать в воображении
rus_verbs:ошеломить{}, // ошеломить в бою
rus_verbs:удостовериться{}, // удостовериться в безопасности
rus_verbs:огласить{}, // огласить в заключительной части
rus_verbs:разбогатеть{}, // разбогатеть в деревне
rus_verbs:грохотать{}, // грохотать в мастерской
rus_verbs:реализоваться{}, // реализоваться в должности
rus_verbs:красть{}, // красть в магазине
rus_verbs:нарваться{}, // нарваться в коридоре
rus_verbs:застывать{}, // застывать в неудобной позе
rus_verbs:толкаться{}, // толкаться в тесной комнате
rus_verbs:извлекать{}, // извлекать в аппарате
rus_verbs:обжигать{}, // обжигать в печи
rus_verbs:запечатлеть{}, // запечатлеть в кинохронике
rus_verbs:тренироваться{}, // тренироваться в зале
rus_verbs:поспорить{}, // поспорить в кабинете
rus_verbs:рыскать{}, // рыскать в лесу
rus_verbs:надрываться{}, // надрываться в шахте
rus_verbs:сняться{}, // сняться в фильме
rus_verbs:закружить{}, // закружить в танце
rus_verbs:затонуть{}, // затонуть в порту
rus_verbs:побыть{}, // побыть в гостях
rus_verbs:почистить{}, // почистить в носу
rus_verbs:сгорбиться{}, // сгорбиться в тесной конуре
rus_verbs:подслушивать{}, // подслушивать в классе
rus_verbs:сгорать{}, // сгорать в танке
rus_verbs:разочароваться{}, // разочароваться в артисте
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать в кустиках
rus_verbs:мять{}, // мять в руках
rus_verbs:подраться{}, // подраться в классе
rus_verbs:замести{}, // замести в прихожей
rus_verbs:откладываться{}, // откладываться в печени
rus_verbs:обозначаться{}, // обозначаться в перечне
rus_verbs:просиживать{}, // просиживать в интернете
rus_verbs:соприкасаться{}, // соприкасаться в точке
rus_verbs:начертить{}, // начертить в тетрадке
rus_verbs:уменьшать{}, // уменьшать в поперечнике
rus_verbs:тормозить{}, // тормозить в облаке
rus_verbs:затевать{}, // затевать в лаборатории
rus_verbs:затопить{}, // затопить в бухте
rus_verbs:задерживать{}, // задерживать в лифте
rus_verbs:прогуляться{}, // прогуляться в лесу
rus_verbs:прорубить{}, // прорубить во льду
rus_verbs:очищать{}, // очищать в кислоте
rus_verbs:полулежать{}, // полулежать в гамаке
rus_verbs:исправить{}, // исправить в задании
rus_verbs:предусматриваться{}, // предусматриваться в постановке задачи
rus_verbs:замучить{}, // замучить в плену
rus_verbs:разрушаться{}, // разрушаться в верхней части
rus_verbs:ерзать{}, // ерзать в кресле
rus_verbs:покопаться{}, // покопаться в залежах
rus_verbs:раскаяться{}, // раскаяться в содеянном
rus_verbs:пробежаться{}, // пробежаться в парке
rus_verbs:полежать{}, // полежать в гамаке
rus_verbs:позаимствовать{}, // позаимствовать в книге
rus_verbs:снижать{}, // снижать в несколько раз
rus_verbs:черпать{}, // черпать в поэзии
rus_verbs:заверять{}, // заверять в своей искренности
rus_verbs:проглядеть{}, // проглядеть в сумерках
rus_verbs:припарковать{}, // припарковать во дворе
rus_verbs:сверлить{}, // сверлить в стене
rus_verbs:здороваться{}, // здороваться в аудитории
rus_verbs:рожать{}, // рожать в воде
rus_verbs:нацарапать{}, // нацарапать в тетрадке
rus_verbs:затопать{}, // затопать в коридоре
rus_verbs:прописать{}, // прописать в правилах
rus_verbs:сориентироваться{}, // сориентироваться в обстоятельствах
rus_verbs:снизить{}, // снизить в несколько раз
rus_verbs:заблуждаться{}, // заблуждаться в своей теории
rus_verbs:откопать{}, // откопать в отвалах
rus_verbs:смастерить{}, // смастерить в лаборатории
rus_verbs:замедлиться{}, // замедлиться в парафине
rus_verbs:избивать{}, // избивать в участке
rus_verbs:мыться{}, // мыться в бане
rus_verbs:сварить{}, // сварить в кастрюльке
rus_verbs:раскопать{}, // раскопать в снегу
rus_verbs:крепиться{}, // крепиться в держателе
rus_verbs:дробить{}, // дробить в мельнице
rus_verbs:попить{}, // попить в ресторанчике
rus_verbs:затронуть{}, // затронуть в душе
rus_verbs:лязгнуть{}, // лязгнуть в тишине
rus_verbs:заправлять{}, // заправлять в полете
rus_verbs:размножаться{}, // размножаться в неволе
rus_verbs:потопить{}, // потопить в Тихом Океане
rus_verbs:кушать{}, // кушать в столовой
rus_verbs:замолкать{}, // замолкать в замешательстве
rus_verbs:измеряться{}, // измеряться в дюймах
rus_verbs:сбываться{}, // сбываться в мечтах
rus_verbs:задернуть{}, // задернуть в комнате
rus_verbs:затихать{}, // затихать в темноте
rus_verbs:прослеживаться{}, // прослеживается в журнале
rus_verbs:прерываться{}, // прерывается в начале
rus_verbs:изображаться{}, // изображается в любых фильмах
rus_verbs:фиксировать{}, // фиксировать в данной точке
rus_verbs:ослаблять{}, // ослаблять в поясе
rus_verbs:зреть{}, // зреть в теплице
rus_verbs:зеленеть{}, // зеленеть в огороде
rus_verbs:критиковать{}, // критиковать в статье
rus_verbs:облететь{}, // облететь в частном вертолете
rus_verbs:разбросать{}, // разбросать в комнате
rus_verbs:заразиться{}, // заразиться в людном месте
rus_verbs:рассеять{}, // рассеять в бою
rus_verbs:печься{}, // печься в духовке
rus_verbs:поспать{}, // поспать в палатке
rus_verbs:заступиться{}, // заступиться в драке
rus_verbs:сплетаться{}, // сплетаться в середине
rus_verbs:поместиться{}, // поместиться в мешке
rus_verbs:спереть{}, // спереть в лавке
// инфинитив:ликвидировать{ вид:несоверш }, глагол:ликвидировать{ вид:несоверш }, // ликвидировать в пригороде
// инфинитив:ликвидировать{ вид:соверш }, глагол:ликвидировать{ вид:соверш },
rus_verbs:проваляться{}, // проваляться в постели
rus_verbs:лечиться{}, // лечиться в стационаре
rus_verbs:определиться{}, // определиться в честном бою
rus_verbs:обработать{}, // обработать в растворе
rus_verbs:пробивать{}, // пробивать в стене
rus_verbs:перемешаться{}, // перемешаться в чане
rus_verbs:чесать{}, // чесать в паху
rus_verbs:пролечь{}, // пролечь в пустынной местности
rus_verbs:скитаться{}, // скитаться в дальних странах
rus_verbs:затрудняться{}, // затрудняться в выборе
rus_verbs:отряхнуться{}, // отряхнуться в коридоре
rus_verbs:разыгрываться{}, // разыгрываться в лотерее
rus_verbs:помолиться{}, // помолиться в церкви
rus_verbs:предписывать{}, // предписывать в рецепте
rus_verbs:порваться{}, // порваться в слабом месте
rus_verbs:греться{}, // греться в здании
rus_verbs:опровергать{}, // опровергать в своем выступлении
rus_verbs:помянуть{}, // помянуть в своем выступлении
rus_verbs:допросить{}, // допросить в прокуратуре
rus_verbs:материализоваться{}, // материализоваться в соседнем здании
rus_verbs:рассеиваться{}, // рассеиваться в воздухе
rus_verbs:перевозить{}, // перевозить в вагоне
rus_verbs:отбывать{}, // отбывать в тюрьме
rus_verbs:попахивать{}, // попахивать в отхожем месте
rus_verbs:перечислять{}, // перечислять в заключении
rus_verbs:зарождаться{}, // зарождаться в дебрях
rus_verbs:предъявлять{}, // предъявлять в своем письме
rus_verbs:распространять{}, // распространять в сети
rus_verbs:пировать{}, // пировать в соседнем селе
rus_verbs:начертать{}, // начертать в летописи
rus_verbs:расцветать{}, // расцветать в подходящих условиях
rus_verbs:царствовать{}, // царствовать в южной части материка
rus_verbs:накопить{}, // накопить в буфере
rus_verbs:закрутиться{}, // закрутиться в рутине
rus_verbs:отработать{}, // отработать в забое
rus_verbs:обокрасть{}, // обокрасть в автобусе
rus_verbs:прокладывать{}, // прокладывать в снегу
rus_verbs:ковырять{}, // ковырять в носу
rus_verbs:копить{}, // копить в очереди
rus_verbs:полечь{}, // полечь в степях
rus_verbs:щебетать{}, // щебетать в кустиках
rus_verbs:подчеркиваться{}, // подчеркиваться в сообщении
rus_verbs:посеять{}, // посеять в огороде
rus_verbs:разъезжать{}, // разъезжать в кабриолете
rus_verbs:замечаться{}, // замечаться в лесу
rus_verbs:просчитать{}, // просчитать в уме
rus_verbs:маяться{}, // маяться в командировке
rus_verbs:выхватывать{}, // выхватывать в тексте
rus_verbs:креститься{}, // креститься в деревенской часовне
rus_verbs:обрабатывать{}, // обрабатывать в растворе кислоты
rus_verbs:настигать{}, // настигать в огороде
rus_verbs:разгуливать{}, // разгуливать в роще
rus_verbs:насиловать{}, // насиловать в квартире
rus_verbs:побороть{}, // побороть в себе
rus_verbs:учитывать{}, // учитывать в расчетах
rus_verbs:искажать{}, // искажать в заметке
rus_verbs:пропить{}, // пропить в кабаке
rus_verbs:катать{}, // катать в лодочке
rus_verbs:припрятать{}, // припрятать в кармашке
rus_verbs:запаниковать{}, // запаниковать в бою
rus_verbs:рассыпать{}, // рассыпать в траве
rus_verbs:застревать{}, // застревать в ограде
rus_verbs:зажигаться{}, // зажигаться в сумерках
rus_verbs:жарить{}, // жарить в масле
rus_verbs:накапливаться{}, // накапливаться в костях
rus_verbs:распуститься{}, // распуститься в горшке
rus_verbs:проголосовать{}, // проголосовать в передвижном пункте
rus_verbs:странствовать{}, // странствовать в автомобиле
rus_verbs:осматриваться{}, // осматриваться в хоромах
rus_verbs:разворачивать{}, // разворачивать в спортзале
rus_verbs:заскучать{}, // заскучать в самолете
rus_verbs:напутать{}, // напутать в расчете
rus_verbs:перекусить{}, // перекусить в столовой
rus_verbs:спасаться{}, // спасаться в автономной капсуле
rus_verbs:посовещаться{}, // посовещаться в комнате
rus_verbs:доказываться{}, // доказываться в статье
rus_verbs:познаваться{}, // познаваться в беде
rus_verbs:загрустить{}, // загрустить в одиночестве
rus_verbs:оживить{}, // оживить в памяти
rus_verbs:переворачиваться{}, // переворачиваться в гробу
rus_verbs:заприметить{}, // заприметить в лесу
rus_verbs:отравиться{}, // отравиться в забегаловке
rus_verbs:продержать{}, // продержать в клетке
rus_verbs:выявить{}, // выявить в костях
rus_verbs:заседать{}, // заседать в совете
rus_verbs:расплачиваться{}, // расплачиваться в первой кассе
rus_verbs:проломить{}, // проломить в двери
rus_verbs:подражать{}, // подражать в мелочах
rus_verbs:подсчитывать{}, // подсчитывать в уме
rus_verbs:опережать{}, // опережать во всем
rus_verbs:сформироваться{}, // сформироваться в облаке
rus_verbs:укрепиться{}, // укрепиться в мнении
rus_verbs:отстоять{}, // отстоять в очереди
rus_verbs:развертываться{}, // развертываться в месте испытания
rus_verbs:замерзать{}, // замерзать во льду
rus_verbs:утопать{}, // утопать в снегу
rus_verbs:раскаиваться{}, // раскаиваться в содеянном
rus_verbs:организовывать{}, // организовывать в пионерлагере
rus_verbs:перевестись{}, // перевестись в наших краях
rus_verbs:смешивать{}, // смешивать в блендере
rus_verbs:ютиться{}, // ютиться в тесной каморке
rus_verbs:прождать{}, // прождать в аудитории
rus_verbs:подыскивать{}, // подыскивать в женском общежитии
rus_verbs:замочить{}, // замочить в сортире
rus_verbs:мерзнуть{}, // мерзнуть в тонкой курточке
rus_verbs:растирать{}, // растирать в ступке
rus_verbs:замедлять{}, // замедлять в парафине
rus_verbs:переспать{}, // переспать в палатке
rus_verbs:рассекать{}, // рассекать в кабриолете
rus_verbs:отыскивать{}, // отыскивать в залежах
rus_verbs:опровергнуть{}, // опровергнуть в своем выступлении
rus_verbs:дрыхнуть{}, // дрыхнуть в гамаке
rus_verbs:укрываться{}, // укрываться в землянке
rus_verbs:запечься{}, // запечься в золе
rus_verbs:догорать{}, // догорать в темноте
rus_verbs:застилать{}, // застилать в коридоре
rus_verbs:сыскаться{}, // сыскаться в деревне
rus_verbs:переделать{}, // переделать в мастерской
rus_verbs:разъяснять{}, // разъяснять в своей лекции
rus_verbs:селиться{}, // селиться в центре
rus_verbs:оплачивать{}, // оплачивать в магазине
rus_verbs:переворачивать{}, // переворачивать в закрытой банке
rus_verbs:упражняться{}, // упражняться в остроумии
rus_verbs:пометить{}, // пометить в списке
rus_verbs:припомниться{}, // припомниться в завещании
rus_verbs:приютить{}, // приютить в амбаре
rus_verbs:натерпеться{}, // натерпеться в темнице
rus_verbs:затеваться{}, // затеваться в клубе
rus_verbs:уплывать{}, // уплывать в лодке
rus_verbs:скиснуть{}, // скиснуть в бидоне
rus_verbs:заколоть{}, // заколоть в боку
rus_verbs:замерцать{}, // замерцать в темноте
rus_verbs:фиксироваться{}, // фиксироваться в протоколе
rus_verbs:запираться{}, // запираться в комнате
rus_verbs:съезжаться{}, // съезжаться в каретах
rus_verbs:толочься{}, // толочься в ступе
rus_verbs:потанцевать{}, // потанцевать в клубе
rus_verbs:побродить{}, // побродить в парке
rus_verbs:назревать{}, // назревать в коллективе
rus_verbs:дохнуть{}, // дохнуть в питомнике
rus_verbs:крестить{}, // крестить в деревенской церквушке
rus_verbs:рассчитаться{}, // рассчитаться в банке
rus_verbs:припарковаться{}, // припарковаться во дворе
rus_verbs:отхватить{}, // отхватить в магазинчике
rus_verbs:остывать{}, // остывать в холодильнике
rus_verbs:составляться{}, // составляться в атмосфере тайны
rus_verbs:переваривать{}, // переваривать в тишине
rus_verbs:хвастать{}, // хвастать в казино
rus_verbs:отрабатывать{}, // отрабатывать в теплице
rus_verbs:разлечься{}, // разлечься в кровати
rus_verbs:прокручивать{}, // прокручивать в голове
rus_verbs:очертить{}, // очертить в воздухе
rus_verbs:сконфузиться{}, // сконфузиться в окружении незнакомых людей
rus_verbs:выявлять{}, // выявлять в боевых условиях
rus_verbs:караулить{}, // караулить в лифте
rus_verbs:расставлять{}, // расставлять в бойницах
rus_verbs:прокрутить{}, // прокрутить в голове
rus_verbs:пересказывать{}, // пересказывать в первой главе
rus_verbs:задавить{}, // задавить в зародыше
rus_verbs:хозяйничать{}, // хозяйничать в холодильнике
rus_verbs:хвалиться{}, // хвалиться в детском садике
rus_verbs:оперировать{}, // оперировать в полевом госпитале
rus_verbs:формулировать{}, // формулировать в следующей главе
rus_verbs:застигнуть{}, // застигнуть в неприглядном виде
rus_verbs:замурлыкать{}, // замурлыкать в тепле
rus_verbs:поддакивать{}, // поддакивать в споре
rus_verbs:прочертить{}, // прочертить в воздухе
rus_verbs:отменять{}, // отменять в городе коменданский час
rus_verbs:колдовать{}, // колдовать в лаборатории
rus_verbs:отвозить{}, // отвозить в машине
rus_verbs:трахать{}, // трахать в гамаке
rus_verbs:повозиться{}, // повозиться в мешке
rus_verbs:ремонтировать{}, // ремонтировать в центре
rus_verbs:робеть{}, // робеть в гостях
rus_verbs:перепробовать{}, // перепробовать в деле
инфинитив:реализовать{ вид:соверш }, инфинитив:реализовать{ вид:несоверш }, // реализовать в новой версии
глагол:реализовать{ вид:соверш }, глагол:реализовать{ вид:несоверш },
rus_verbs:покаяться{}, // покаяться в церкви
rus_verbs:попрыгать{}, // попрыгать в бассейне
rus_verbs:умалчивать{}, // умалчивать в своем докладе
rus_verbs:ковыряться{}, // ковыряться в старой технике
rus_verbs:расписывать{}, // расписывать в деталях
rus_verbs:вязнуть{}, // вязнуть в песке
rus_verbs:погрязнуть{}, // погрязнуть в скандалах
rus_verbs:корениться{}, // корениться в неспособности выполнить поставленную задачу
rus_verbs:зажимать{}, // зажимать в углу
rus_verbs:стискивать{}, // стискивать в ладонях
rus_verbs:практиковаться{}, // практиковаться в приготовлении соуса
rus_verbs:израсходовать{}, // израсходовать в полете
rus_verbs:клокотать{}, // клокотать в жерле
rus_verbs:обвиняться{}, // обвиняться в растрате
rus_verbs:уединиться{}, // уединиться в кладовке
rus_verbs:подохнуть{}, // подохнуть в болоте
rus_verbs:кипятиться{}, // кипятиться в чайнике
rus_verbs:уродиться{}, // уродиться в лесу
rus_verbs:продолжиться{}, // продолжиться в баре
rus_verbs:расшифровать{}, // расшифровать в специальном устройстве
rus_verbs:посапывать{}, // посапывать в кровати
rus_verbs:скрючиться{}, // скрючиться в мешке
rus_verbs:лютовать{}, // лютовать в отдаленных селах
rus_verbs:расписать{}, // расписать в статье
rus_verbs:публиковаться{}, // публиковаться в научном журнале
rus_verbs:зарегистрировать{}, // зарегистрировать в комитете
rus_verbs:прожечь{}, // прожечь в листе
rus_verbs:переждать{}, // переждать в окопе
rus_verbs:публиковать{}, // публиковать в журнале
rus_verbs:морщить{}, // морщить в уголках глаз
rus_verbs:спиться{}, // спиться в одиночестве
rus_verbs:изведать{}, // изведать в гареме
rus_verbs:обмануться{}, // обмануться в ожиданиях
rus_verbs:сочетать{}, // сочетать в себе
rus_verbs:подрабатывать{}, // подрабатывать в магазине
rus_verbs:репетировать{}, // репетировать в студии
rus_verbs:рябить{}, // рябить в глазах
rus_verbs:намочить{}, // намочить в луже
rus_verbs:скатать{}, // скатать в руке
rus_verbs:одевать{}, // одевать в магазине
rus_verbs:испечь{}, // испечь в духовке
rus_verbs:сбрить{}, // сбрить в подмышках
rus_verbs:зажужжать{}, // зажужжать в ухе
rus_verbs:сберечь{}, // сберечь в тайном месте
rus_verbs:согреться{}, // согреться в хижине
инфинитив:дебютировать{ вид:несоверш }, инфинитив:дебютировать{ вид:соверш }, // дебютировать в спектакле
глагол:дебютировать{ вид:несоверш }, глагол:дебютировать{ вид:соверш },
rus_verbs:переплыть{}, // переплыть в лодочке
rus_verbs:передохнуть{}, // передохнуть в тени
rus_verbs:отсвечивать{}, // отсвечивать в зеркалах
rus_verbs:переправляться{}, // переправляться в лодках
rus_verbs:накупить{}, // накупить в магазине
rus_verbs:проторчать{}, // проторчать в очереди
rus_verbs:проскальзывать{}, // проскальзывать в сообщениях
rus_verbs:застукать{}, // застукать в солярии
rus_verbs:наесть{}, // наесть в отпуске
rus_verbs:подвизаться{}, // подвизаться в новом деле
rus_verbs:вычистить{}, // вычистить в саду
rus_verbs:кормиться{}, // кормиться в лесу
rus_verbs:покурить{}, // покурить в саду
rus_verbs:понизиться{}, // понизиться в ранге
rus_verbs:зимовать{}, // зимовать в избушке
rus_verbs:проверяться{}, // проверяться в службе безопасности
rus_verbs:подпирать{}, // подпирать в первом забое
rus_verbs:кувыркаться{}, // кувыркаться в постели
rus_verbs:похрапывать{}, // похрапывать в постели
rus_verbs:завязнуть{}, // завязнуть в песке
rus_verbs:трактовать{}, // трактовать в исследовательской статье
rus_verbs:замедляться{}, // замедляться в тяжелой воде
rus_verbs:шастать{}, // шастать в здании
rus_verbs:заночевать{}, // заночевать в пути
rus_verbs:наметиться{}, // наметиться в исследованиях рака
rus_verbs:освежить{}, // освежить в памяти
rus_verbs:оспаривать{}, // оспаривать в суде
rus_verbs:умещаться{}, // умещаться в ячейке
rus_verbs:искупить{}, // искупить в бою
rus_verbs:отсиживаться{}, // отсиживаться в тылу
rus_verbs:мчать{}, // мчать в кабриолете
rus_verbs:обличать{}, // обличать в своем выступлении
rus_verbs:сгнить{}, // сгнить в тюряге
rus_verbs:опробовать{}, // опробовать в деле
rus_verbs:тренировать{}, // тренировать в зале
rus_verbs:прославить{}, // прославить в академии
rus_verbs:учитываться{}, // учитываться в дипломной работе
rus_verbs:повеселиться{}, // повеселиться в лагере
rus_verbs:поумнеть{}, // поумнеть в карцере
rus_verbs:перестрелять{}, // перестрелять в воздухе
rus_verbs:проведать{}, // проведать в больнице
rus_verbs:измучиться{}, // измучиться в деревне
rus_verbs:прощупать{}, // прощупать в глубине
rus_verbs:изготовлять{}, // изготовлять в сарае
rus_verbs:свирепствовать{}, // свирепствовать в популяции
rus_verbs:иссякать{}, // иссякать в источнике
rus_verbs:гнездиться{}, // гнездиться в дупле
rus_verbs:разогнаться{}, // разогнаться в спортивной машине
rus_verbs:опознавать{}, // опознавать в неизвестном
rus_verbs:засвидетельствовать{}, // засвидетельствовать в суде
rus_verbs:сконцентрировать{}, // сконцентрировать в своих руках
rus_verbs:редактировать{}, // редактировать в редакторе
rus_verbs:покупаться{}, // покупаться в магазине
rus_verbs:промышлять{}, // промышлять в роще
rus_verbs:растягиваться{}, // растягиваться в коридоре
rus_verbs:приобретаться{}, // приобретаться в антикварных лавках
инфинитив:подрезать{ вид:несоверш }, инфинитив:подрезать{ вид:соверш }, // подрезать в воде
глагол:подрезать{ вид:несоверш }, глагол:подрезать{ вид:соверш },
rus_verbs:запечатлеться{}, // запечатлеться в мозгу
rus_verbs:укрывать{}, // укрывать в подвале
rus_verbs:закрепиться{}, // закрепиться в первой башне
rus_verbs:освежать{}, // освежать в памяти
rus_verbs:громыхать{}, // громыхать в ванной
инфинитив:подвигаться{ вид:соверш }, инфинитив:подвигаться{ вид:несоверш }, // подвигаться в кровати
глагол:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:несоверш },
rus_verbs:добываться{}, // добываться в шахтах
rus_verbs:растворить{}, // растворить в кислоте
rus_verbs:приплясывать{}, // приплясывать в гримерке
rus_verbs:доживать{}, // доживать в доме престарелых
rus_verbs:отпраздновать{}, // отпраздновать в ресторане
rus_verbs:сотрясаться{}, // сотрясаться в конвульсиях
rus_verbs:помыть{}, // помыть в проточной воде
инфинитив:увязать{ вид:несоверш }, инфинитив:увязать{ вид:соверш }, // увязать в песке
глагол:увязать{ вид:несоверш }, глагол:увязать{ вид:соверш },
прилагательное:увязавший{ вид:несоверш },
rus_verbs:наличествовать{}, // наличествовать в запаснике
rus_verbs:нащупывать{}, // нащупывать в кармане
rus_verbs:повествоваться{}, // повествоваться в рассказе
rus_verbs:отремонтировать{}, // отремонтировать в техцентре
rus_verbs:покалывать{}, // покалывать в правом боку
rus_verbs:сиживать{}, // сиживать в саду
rus_verbs:разрабатываться{}, // разрабатываться в секретных лабораториях
rus_verbs:укрепляться{}, // укрепляться в мнении
rus_verbs:разниться{}, // разниться во взглядах
rus_verbs:сполоснуть{}, // сполоснуть в водичке
rus_verbs:скупать{}, // скупать в магазине
rus_verbs:почесывать{}, // почесывать в паху
rus_verbs:оформлять{}, // оформлять в конторе
rus_verbs:распускаться{}, // распускаться в садах
rus_verbs:зарябить{}, // зарябить в глазах
rus_verbs:загореть{}, // загореть в Испании
rus_verbs:очищаться{}, // очищаться в баке
rus_verbs:остудить{}, // остудить в холодной воде
rus_verbs:разбомбить{}, // разбомбить в горах
rus_verbs:издохнуть{}, // издохнуть в бедности
rus_verbs:проехаться{}, // проехаться в новой машине
rus_verbs:задействовать{}, // задействовать в анализе
rus_verbs:произрастать{}, // произрастать в степи
rus_verbs:разуться{}, // разуться в прихожей
rus_verbs:сооружать{}, // сооружать в огороде
rus_verbs:зачитывать{}, // зачитывать в суде
rus_verbs:состязаться{}, // состязаться в остроумии
rus_verbs:ополоснуть{}, // ополоснуть в молоке
rus_verbs:уместиться{}, // уместиться в кармане
rus_verbs:совершенствоваться{}, // совершенствоваться в управлении мотоциклом
rus_verbs:стираться{}, // стираться в стиральной машине
rus_verbs:искупаться{}, // искупаться в прохладной реке
rus_verbs:курировать{}, // курировать в правительстве
rus_verbs:закупить{}, // закупить в магазине
rus_verbs:плодиться{}, // плодиться в подходящих условиях
rus_verbs:горланить{}, // горланить в парке
rus_verbs:першить{}, // першить в горле
rus_verbs:пригрезиться{}, // пригрезиться во сне
rus_verbs:исправлять{}, // исправлять в тетрадке
rus_verbs:расслабляться{}, // расслабляться в гамаке
rus_verbs:скапливаться{}, // скапливаться в нижней части
rus_verbs:сплетничать{}, // сплетничают в комнате
rus_verbs:раздевать{}, // раздевать в кабинке
rus_verbs:окопаться{}, // окопаться в лесу
rus_verbs:загорать{}, // загорать в Испании
rus_verbs:подпевать{}, // подпевать в церковном хоре
rus_verbs:прожужжать{}, // прожужжать в динамике
rus_verbs:изучаться{}, // изучаться в дикой природе
rus_verbs:заклубиться{}, // заклубиться в воздухе
rus_verbs:подметать{}, // подметать в зале
rus_verbs:подозреваться{}, // подозреваться в совершении кражи
rus_verbs:обогащать{}, // обогащать в специальном аппарате
rus_verbs:издаться{}, // издаться в другом издательстве
rus_verbs:справить{}, // справить в кустах нужду
rus_verbs:помыться{}, // помыться в бане
rus_verbs:проскакивать{}, // проскакивать в словах
rus_verbs:попивать{}, // попивать в кафе чай
rus_verbs:оформляться{}, // оформляться в регистратуре
rus_verbs:чирикать{}, // чирикать в кустах
rus_verbs:скупить{}, // скупить в магазинах
rus_verbs:переночевать{}, // переночевать в гостинице
rus_verbs:концентрироваться{}, // концентрироваться в пробирке
rus_verbs:одичать{}, // одичать в лесу
rus_verbs:ковырнуть{}, // ковырнуть в ухе
rus_verbs:затеплиться{}, // затеплиться в глубине души
rus_verbs:разгрести{}, // разгрести в задачах залежи
rus_verbs:застопориться{}, // застопориться в начале списка
rus_verbs:перечисляться{}, // перечисляться во введении
rus_verbs:покататься{}, // покататься в парке аттракционов
rus_verbs:изловить{}, // изловить в поле
rus_verbs:прославлять{}, // прославлять в стихах
rus_verbs:промочить{}, // промочить в луже
rus_verbs:поделывать{}, // поделывать в отпуске
rus_verbs:просуществовать{}, // просуществовать в первобытном состоянии
rus_verbs:подстеречь{}, // подстеречь в подъезде
rus_verbs:прикупить{}, // прикупить в магазине
rus_verbs:перемешивать{}, // перемешивать в кастрюле
rus_verbs:тискать{}, // тискать в углу
rus_verbs:купать{}, // купать в теплой водичке
rus_verbs:завариться{}, // завариться в стакане
rus_verbs:притулиться{}, // притулиться в углу
rus_verbs:пострелять{}, // пострелять в тире
rus_verbs:навесить{}, // навесить в больнице
инфинитив:изолировать{ вид:соверш }, инфинитив:изолировать{ вид:несоверш }, // изолировать в камере
глагол:изолировать{ вид:соверш }, глагол:изолировать{ вид:несоверш },
rus_verbs:нежиться{}, // нежится в постельке
rus_verbs:притомиться{}, // притомиться в школе
rus_verbs:раздвоиться{}, // раздвоиться в глазах
rus_verbs:навалить{}, // навалить в углу
rus_verbs:замуровать{}, // замуровать в склепе
rus_verbs:поселяться{}, // поселяться в кроне дуба
rus_verbs:потягиваться{}, // потягиваться в кровати
rus_verbs:укачать{}, // укачать в поезде
rus_verbs:отлеживаться{}, // отлеживаться в гамаке
rus_verbs:разменять{}, // разменять в кассе
rus_verbs:прополоскать{}, // прополоскать в чистой теплой воде
rus_verbs:ржаветь{}, // ржаветь в воде
rus_verbs:уличить{}, // уличить в плагиате
rus_verbs:мутиться{}, // мутиться в голове
rus_verbs:растворять{}, // растворять в бензоле
rus_verbs:двоиться{}, // двоиться в глазах
rus_verbs:оговорить{}, // оговорить в договоре
rus_verbs:подделать{}, // подделать в документе
rus_verbs:зарегистрироваться{}, // зарегистрироваться в социальной сети
rus_verbs:растолстеть{}, // растолстеть в талии
rus_verbs:повоевать{}, // повоевать в городских условиях
rus_verbs:прибраться{}, // гнушаться прибраться в хлеву
rus_verbs:поглощаться{}, // поглощаться в металлической фольге
rus_verbs:ухать{}, // ухать в лесу
rus_verbs:подписываться{}, // подписываться в петиции
rus_verbs:покатать{}, // покатать в машинке
rus_verbs:излечиться{}, // излечиться в клинике
rus_verbs:трепыхаться{}, // трепыхаться в мешке
rus_verbs:кипятить{}, // кипятить в кастрюле
rus_verbs:понастроить{}, // понастроить в прибрежной зоне
rus_verbs:перебывать{}, // перебывать во всех европейских столицах
rus_verbs:оглашать{}, // оглашать в итоговой части
rus_verbs:преуспевать{}, // преуспевать в новом бизнесе
rus_verbs:консультироваться{}, // консультироваться в техподдержке
rus_verbs:накапливать{}, // накапливать в печени
rus_verbs:перемешать{}, // перемешать в контейнере
rus_verbs:наследить{}, // наследить в коридоре
rus_verbs:выявиться{}, // выявиться в результе
rus_verbs:забулькать{}, // забулькать в болоте
rus_verbs:отваривать{}, // отваривать в молоке
rus_verbs:запутываться{}, // запутываться в веревках
rus_verbs:нагреться{}, // нагреться в микроволновой печке
rus_verbs:рыбачить{}, // рыбачить в открытом море
rus_verbs:укорениться{}, // укорениться в сознании широких народных масс
rus_verbs:умывать{}, // умывать в тазике
rus_verbs:защекотать{}, // защекотать в носу
rus_verbs:заходиться{}, // заходиться в плаче
инфинитив:искупать{ вид:соверш }, инфинитив:искупать{ вид:несоверш }, // искупать в прохладной водичке
глагол:искупать{ вид:соверш }, глагол:искупать{ вид:несоверш },
деепричастие:искупав{}, деепричастие:искупая{},
rus_verbs:заморозить{}, // заморозить в холодильнике
rus_verbs:закреплять{}, // закреплять в металлическом держателе
rus_verbs:расхватать{}, // расхватать в магазине
rus_verbs:истязать{}, // истязать в тюремном подвале
rus_verbs:заржаветь{}, // заржаветь во влажной атмосфере
rus_verbs:обжаривать{}, // обжаривать в подсолнечном масле
rus_verbs:умереть{}, // Ты, подлый предатель, умрешь в нищете
rus_verbs:подогреть{}, // подогрей в микроволновке
rus_verbs:подогревать{},
rus_verbs:затянуть{}, // Кузнечики, сверчки, скрипачи и медведки затянули в траве свою трескучую музыку
rus_verbs:проделать{}, // проделать в стене дыру
инфинитив:жениться{ вид:соверш }, // жениться в Техасе
инфинитив:жениться{ вид:несоверш },
глагол:жениться{ вид:соверш },
глагол:жениться{ вид:несоверш },
деепричастие:женившись{},
деепричастие:женясь{},
прилагательное:женатый{},
прилагательное:женившийся{вид:соверш},
прилагательное:женящийся{},
rus_verbs:всхрапнуть{}, // всхрапнуть во сне
rus_verbs:всхрапывать{}, // всхрапывать во сне
rus_verbs:ворочаться{}, // Собака ворочается во сне
rus_verbs:воссоздаваться{}, // воссоздаваться в памяти
rus_verbs:акклиматизироваться{}, // альпинисты готовятся акклиматизироваться в горах
инфинитив:атаковать{ вид:несоверш }, // взвод был атакован в лесу
инфинитив:атаковать{ вид:соверш },
глагол:атаковать{ вид:несоверш },
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{},
прилагательное:атаковавший{},
прилагательное:атакующий{},
инфинитив:аккумулировать{вид:несоверш}, // энергия была аккумулирована в печени
инфинитив:аккумулировать{вид:соверш},
глагол:аккумулировать{вид:несоверш},
глагол:аккумулировать{вид:соверш},
прилагательное:аккумулированный{},
прилагательное:аккумулирующий{},
//прилагательное:аккумулировавший{ вид:несоверш },
прилагательное:аккумулировавший{ вид:соверш },
rus_verbs:врисовывать{}, // врисовывать нового персонажа в анимацию
rus_verbs:вырасти{}, // Он вырос в глазах коллег.
rus_verbs:иметь{}, // Он всегда имел в резерве острое словцо.
rus_verbs:убить{}, // убить в себе зверя
инфинитив:абсорбироваться{ вид:соверш }, // жидкость абсорбируется в поглощающей ткани
инфинитив:абсорбироваться{ вид:несоверш },
глагол:абсорбироваться{ вид:соверш },
глагол:абсорбироваться{ вид:несоверш },
rus_verbs:поставить{}, // поставить в углу
rus_verbs:сжимать{}, // сжимать в кулаке
rus_verbs:готовиться{}, // альпинисты готовятся акклиматизироваться в горах
rus_verbs:аккумулироваться{}, // энергия аккумулируется в жировых отложениях
инфинитив:активизироваться{ вид:несоверш }, // в горах активизировались повстанцы
инфинитив:активизироваться{ вид:соверш },
глагол:активизироваться{ вид:несоверш },
глагол:активизироваться{ вид:соверш },
rus_verbs:апробировать{}, // пилот апробировал в ходе испытаний новый режим планера
rus_verbs:арестовать{}, // наркодилер был арестован в помещении кафе
rus_verbs:базировать{}, // установка будет базирована в лесу
rus_verbs:барахтаться{}, // дети барахтались в воде
rus_verbs:баррикадироваться{}, // преступники баррикадируются в помещении банка
rus_verbs:барствовать{}, // Семен Семенович барствовал в своей деревне
rus_verbs:бесчинствовать{}, // Боевики бесчинствовали в захваченном селе
rus_verbs:блаженствовать{}, // Воробьи блаженствовали в кроне рябины
rus_verbs:блуждать{}, // Туристы блуждали в лесу
rus_verbs:брать{}, // Жена берет деньги в тумбочке
rus_verbs:бродить{}, // парочки бродили в парке
rus_verbs:обойти{}, // Бразилия обошла Россию в рейтинге
rus_verbs:задержать{}, // Знаменитый советский фигурист задержан в США
rus_verbs:бултыхаться{}, // Ноги бултыхаются в воде
rus_verbs:вариться{}, // Курица варится в кастрюле
rus_verbs:закончиться{}, // Эта рецессия закончилась в 2003 году
rus_verbs:прокручиваться{}, // Ключ прокручивается в замке
rus_verbs:прокрутиться{}, // Ключ трижды прокрутился в замке
rus_verbs:храниться{}, // Настройки хранятся в текстовом файле
rus_verbs:сохраняться{}, // Настройки сохраняются в текстовом файле
rus_verbs:витать{}, // Мальчик витает в облаках
rus_verbs:владычествовать{}, // Король владычествует в стране
rus_verbs:властвовать{}, // Олигархи властвовали в стране
rus_verbs:возбудить{}, // возбудить в сердце тоску
rus_verbs:возбуждать{}, // возбуждать в сердце тоску
rus_verbs:возвыситься{}, // возвыситься в глазах современников
rus_verbs:возжечь{}, // возжечь в храме огонь
rus_verbs:возжечься{}, // Огонь возжёгся в храме
rus_verbs:возжигать{}, // возжигать в храме огонь
rus_verbs:возжигаться{}, // Огонь возжигается в храме
rus_verbs:вознамериваться{}, // вознамериваться уйти в монастырь
rus_verbs:вознамериться{}, // вознамериться уйти в монастырь
rus_verbs:возникать{}, // Новые идеи неожиданно возникают в колиной голове
rus_verbs:возникнуть{}, // Новые идейки возникли в голове
rus_verbs:возродиться{}, // возродиться в новом качестве
rus_verbs:возрождать{}, // возрождать в новом качестве
rus_verbs:возрождаться{}, // возрождаться в новом амплуа
rus_verbs:ворошить{}, // ворошить в камине кочергой золу
rus_verbs:воспевать{}, // Поэты воспевают героев в одах
rus_verbs:воспеваться{}, // Герои воспеваются в одах поэтами
rus_verbs:воспеть{}, // Поэты воспели в этой оде героев
rus_verbs:воспретить{}, // воспретить в помещении азартные игры
rus_verbs:восславить{}, // Поэты восславили в одах
rus_verbs:восславлять{}, // Поэты восславляют в одах
rus_verbs:восславляться{}, // Героя восславляются в одах
rus_verbs:воссоздать{}, // воссоздает в памяти образ человека
rus_verbs:воссоздавать{}, // воссоздать в памяти образ человека
rus_verbs:воссоздаться{}, // воссоздаться в памяти
rus_verbs:вскипятить{}, // вскипятить в чайнике воду
rus_verbs:вскипятиться{}, // вскипятиться в чайнике
rus_verbs:встретить{}, // встретить в классе старого приятеля
rus_verbs:встретиться{}, // встретиться в классе
rus_verbs:встречать{}, // встречать в лесу голодного медведя
rus_verbs:встречаться{}, // встречаться в кафе
rus_verbs:выбривать{}, // выбривать что-то в подмышках
rus_verbs:выбрить{}, // выбрить что-то в паху
rus_verbs:вывалять{}, // вывалять кого-то в грязи
rus_verbs:вываляться{}, // вываляться в грязи
rus_verbs:вываривать{}, // вываривать в молоке
rus_verbs:вывариваться{}, // вывариваться в молоке
rus_verbs:выварить{}, // выварить в молоке
rus_verbs:вывариться{}, // вывариться в молоке
rus_verbs:выгрызать{}, // выгрызать в сыре отверствие
rus_verbs:выгрызть{}, // выгрызть в сыре отверстие
rus_verbs:выгуливать{}, // выгуливать в парке собаку
rus_verbs:выгулять{}, // выгулять в парке собаку
rus_verbs:выдолбить{}, // выдолбить в стволе углубление
rus_verbs:выжить{}, // выжить в пустыне
rus_verbs:Выискать{}, // Выискать в программе ошибку
rus_verbs:выискаться{}, // Ошибка выискалась в программе
rus_verbs:выискивать{}, // выискивать в программе ошибку
rus_verbs:выискиваться{}, // выискиваться в программе
rus_verbs:выкраивать{}, // выкраивать в расписании время
rus_verbs:выкраиваться{}, // выкраиваться в расписании
инфинитив:выкупаться{aux stress="в^ыкупаться"}, // выкупаться в озере
глагол:выкупаться{вид:соверш},
rus_verbs:выловить{}, // выловить в пруду
rus_verbs:вымачивать{}, // вымачивать в молоке
rus_verbs:вымачиваться{}, // вымачиваться в молоке
rus_verbs:вынюхивать{}, // вынюхивать в траве следы
rus_verbs:выпачкать{}, // выпачкать в смоле свою одежду
rus_verbs:выпачкаться{}, // выпачкаться в грязи
rus_verbs:вырастить{}, // вырастить в теплице ведро огурчиков
rus_verbs:выращивать{}, // выращивать в теплице помидоры
rus_verbs:выращиваться{}, // выращиваться в теплице
rus_verbs:вырыть{}, // вырыть в земле глубокую яму
rus_verbs:высадить{}, // высадить в пустынной местности
rus_verbs:высадиться{}, // высадиться в пустынной местности
rus_verbs:высаживать{}, // высаживать в пустыне
rus_verbs:высверливать{}, // высверливать в доске отверствие
rus_verbs:высверливаться{}, // высверливаться в стене
rus_verbs:высверлить{}, // высверлить в стене отверствие
rus_verbs:высверлиться{}, // высверлиться в стене
rus_verbs:выскоблить{}, // выскоблить в столешнице канавку
rus_verbs:высматривать{}, // высматривать в темноте
rus_verbs:заметить{}, // заметить в помещении
rus_verbs:оказаться{}, // оказаться в первых рядах
rus_verbs:душить{}, // душить в объятиях
rus_verbs:оставаться{}, // оставаться в классе
rus_verbs:появиться{}, // впервые появиться в фильме
rus_verbs:лежать{}, // лежать в футляре
rus_verbs:раздаться{}, // раздаться в плечах
rus_verbs:ждать{}, // ждать в здании вокзала
rus_verbs:жить{}, // жить в трущобах
rus_verbs:постелить{}, // постелить в прихожей
rus_verbs:оказываться{}, // оказываться в неприятной ситуации
rus_verbs:держать{}, // держать в голове
rus_verbs:обнаружить{}, // обнаружить в себе способность
rus_verbs:начинать{}, // начинать в лаборатории
rus_verbs:рассказывать{}, // рассказывать в лицах
rus_verbs:ожидать{}, // ожидать в помещении
rus_verbs:продолжить{}, // продолжить в помещении
rus_verbs:состоять{}, // состоять в группе
rus_verbs:родиться{}, // родиться в рубашке
rus_verbs:искать{}, // искать в кармане
rus_verbs:иметься{}, // иметься в наличии
rus_verbs:говориться{}, // говориться в среде панков
rus_verbs:клясться{}, // клясться в верности
rus_verbs:узнавать{}, // узнавать в нем своего сына
rus_verbs:признаться{}, // признаться в ошибке
rus_verbs:сомневаться{}, // сомневаться в искренности
rus_verbs:толочь{}, // толочь в ступе
rus_verbs:понадобиться{}, // понадобиться в суде
rus_verbs:служить{}, // служить в пехоте
rus_verbs:потолочь{}, // потолочь в ступе
rus_verbs:появляться{}, // появляться в театре
rus_verbs:сжать{}, // сжать в объятиях
rus_verbs:действовать{}, // действовать в постановке
rus_verbs:селить{}, // селить в гостинице
rus_verbs:поймать{}, // поймать в лесу
rus_verbs:увидать{}, // увидать в толпе
rus_verbs:подождать{}, // подождать в кабинете
rus_verbs:прочесть{}, // прочесть в глазах
rus_verbs:тонуть{}, // тонуть в реке
rus_verbs:ощущать{}, // ощущать в животе
rus_verbs:ошибиться{}, // ошибиться в расчетах
rus_verbs:отметить{}, // отметить в списке
rus_verbs:показывать{}, // показывать в динамике
rus_verbs:скрыться{}, // скрыться в траве
rus_verbs:убедиться{}, // убедиться в корректности
rus_verbs:прозвучать{}, // прозвучать в наушниках
rus_verbs:разговаривать{}, // разговаривать в фойе
rus_verbs:издать{}, // издать в России
rus_verbs:прочитать{}, // прочитать в газете
rus_verbs:попробовать{}, // попробовать в деле
rus_verbs:замечать{}, // замечать в программе ошибку
rus_verbs:нести{}, // нести в руках
rus_verbs:пропасть{}, // пропасть в плену
rus_verbs:носить{}, // носить в кармане
rus_verbs:гореть{}, // гореть в аду
rus_verbs:поправить{}, // поправить в программе
rus_verbs:застыть{}, // застыть в неудобной позе
rus_verbs:получать{}, // получать в кассе
rus_verbs:потребоваться{}, // потребоваться в работе
rus_verbs:спрятать{}, // спрятать в шкафу
rus_verbs:учиться{}, // учиться в институте
rus_verbs:развернуться{}, // развернуться в коридоре
rus_verbs:подозревать{}, // подозревать в мошенничестве
rus_verbs:играть{}, // играть в команде
rus_verbs:сыграть{}, // сыграть в команде
rus_verbs:строить{}, // строить в деревне
rus_verbs:устроить{}, // устроить в доме вечеринку
rus_verbs:находить{}, // находить в лесу
rus_verbs:нуждаться{}, // нуждаться в деньгах
rus_verbs:испытать{}, // испытать в рабочей обстановке
rus_verbs:мелькнуть{}, // мелькнуть в прицеле
rus_verbs:очутиться{}, // очутиться в закрытом помещении
инфинитив:использовать{вид:соверш}, // использовать в работе
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
глагол:использовать{вид:соверш},
rus_verbs:лететь{}, // лететь в самолете
rus_verbs:смеяться{}, // смеяться в цирке
rus_verbs:ездить{}, // ездить в лимузине
rus_verbs:заснуть{}, // заснуть в неудобной позе
rus_verbs:застать{}, // застать в неформальной обстановке
rus_verbs:очнуться{}, // очнуться в незнакомой обстановке
rus_verbs:твориться{}, // Что творится в закрытой зоне
rus_verbs:разглядеть{}, // разглядеть в темноте
rus_verbs:изучать{}, // изучать в естественных условиях
rus_verbs:удержаться{}, // удержаться в седле
rus_verbs:побывать{}, // побывать в зоопарке
rus_verbs:уловить{}, // уловить в словах нотку отчаяния
rus_verbs:приобрести{}, // приобрести в лавке
rus_verbs:исчезать{}, // исчезать в тумане
rus_verbs:уверять{}, // уверять в своей невиновности
rus_verbs:продолжаться{}, // продолжаться в воздухе
rus_verbs:открывать{}, // открывать в городе новый стадион
rus_verbs:поддержать{}, // поддержать в парке порядок
rus_verbs:солить{}, // солить в бочке
rus_verbs:прожить{}, // прожить в деревне
rus_verbs:создавать{}, // создавать в театре
rus_verbs:обсуждать{}, // обсуждать в коллективе
rus_verbs:заказать{}, // заказать в магазине
rus_verbs:отыскать{}, // отыскать в гараже
rus_verbs:уснуть{}, // уснуть в кресле
rus_verbs:задержаться{}, // задержаться в театре
rus_verbs:подобрать{}, // подобрать в коллекции
rus_verbs:пробовать{}, // пробовать в работе
rus_verbs:курить{}, // курить в закрытом помещении
rus_verbs:устраивать{}, // устраивать в лесу засаду
rus_verbs:установить{}, // установить в багажнике
rus_verbs:запереть{}, // запереть в сарае
rus_verbs:содержать{}, // содержать в достатке
rus_verbs:синеть{}, // синеть в кислородной атмосфере
rus_verbs:слышаться{}, // слышаться в голосе
rus_verbs:закрыться{}, // закрыться в здании
rus_verbs:скрываться{}, // скрываться в квартире
rus_verbs:родить{}, // родить в больнице
rus_verbs:описать{}, // описать в заметках
rus_verbs:перехватить{}, // перехватить в коридоре
rus_verbs:менять{}, // менять в магазине
rus_verbs:скрывать{}, // скрывать в чужой квартире
rus_verbs:стиснуть{}, // стиснуть в стальных объятиях
rus_verbs:останавливаться{}, // останавливаться в гостинице
rus_verbs:мелькать{}, // мелькать в телевизоре
rus_verbs:присутствовать{}, // присутствовать в аудитории
rus_verbs:украсть{}, // украсть в магазине
rus_verbs:победить{}, // победить в войне
rus_verbs:расположиться{}, // расположиться в гостинице
rus_verbs:упомянуть{}, // упомянуть в своей книге
rus_verbs:плыть{}, // плыть в старой бочке
rus_verbs:нащупать{}, // нащупать в глубине
rus_verbs:проявляться{}, // проявляться в работе
rus_verbs:затихнуть{}, // затихнуть в норе
rus_verbs:построить{}, // построить в гараже
rus_verbs:поддерживать{}, // поддерживать в исправном состоянии
rus_verbs:заработать{}, // заработать в стартапе
rus_verbs:сломать{}, // сломать в суставе
rus_verbs:снимать{}, // снимать в гардеробе
rus_verbs:сохранить{}, // сохранить в коллекции
rus_verbs:располагаться{}, // располагаться в отдельном кабинете
rus_verbs:сражаться{}, // сражаться в честном бою
rus_verbs:спускаться{}, // спускаться в батискафе
rus_verbs:уничтожить{}, // уничтожить в схроне
rus_verbs:изучить{}, // изучить в естественных условиях
rus_verbs:рождаться{}, // рождаться в муках
rus_verbs:пребывать{}, // пребывать в прострации
rus_verbs:прилететь{}, // прилететь в аэробусе
rus_verbs:догнать{}, // догнать в переулке
rus_verbs:изобразить{}, // изобразить в танце
rus_verbs:проехать{}, // проехать в легковушке
rus_verbs:убедить{}, // убедить в разумности
rus_verbs:приготовить{}, // приготовить в духовке
rus_verbs:собирать{}, // собирать в лесу
rus_verbs:поплыть{}, // поплыть в катере
rus_verbs:доверять{}, // доверять в управлении
rus_verbs:разобраться{}, // разобраться в законах
rus_verbs:ловить{}, // ловить в озере
rus_verbs:проесть{}, // проесть в куске металла отверстие
rus_verbs:спрятаться{}, // спрятаться в подвале
rus_verbs:провозгласить{}, // провозгласить в речи
rus_verbs:изложить{}, // изложить в своём выступлении
rus_verbs:замяться{}, // замяться в коридоре
rus_verbs:раздаваться{}, // Крик ягуара раздается в джунглях
rus_verbs:доказать{}, // Автор доказал в своей работе, что теорема верна
rus_verbs:хранить{}, // хранить в шкатулке
rus_verbs:шутить{}, // шутить в классе
глагол:рассыпаться{ aux stress="рассып^аться" }, // рассыпаться в извинениях
инфинитив:рассыпаться{ aux stress="рассып^аться" },
rus_verbs:чертить{}, // чертить в тетрадке
rus_verbs:отразиться{}, // отразиться в аттестате
rus_verbs:греть{}, // греть в микроволновке
rus_verbs:зарычать{}, // Кто-то зарычал в глубине леса
rus_verbs:рассуждать{}, // Автор рассуждает в своей статье
rus_verbs:освободить{}, // Обвиняемые были освобождены в зале суда
rus_verbs:окружать{}, // окружать в лесу
rus_verbs:сопровождать{}, // сопровождать в операции
rus_verbs:заканчиваться{}, // заканчиваться в дороге
rus_verbs:поселиться{}, // поселиться в загородном доме
rus_verbs:охватывать{}, // охватывать в хронологии
rus_verbs:запеть{}, // запеть в кино
инфинитив:провозить{вид:несоверш}, // провозить в багаже
глагол:провозить{вид:несоверш},
rus_verbs:мочить{}, // мочить в сортире
rus_verbs:перевернуться{}, // перевернуться в полёте
rus_verbs:улететь{}, // улететь в теплые края
rus_verbs:сдержать{}, // сдержать в руках
rus_verbs:преследовать{}, // преследовать в любой другой стране
rus_verbs:драться{}, // драться в баре
rus_verbs:просидеть{}, // просидеть в классе
rus_verbs:убираться{}, // убираться в квартире
rus_verbs:содрогнуться{}, // содрогнуться в приступе отвращения
rus_verbs:пугать{}, // пугать в прессе
rus_verbs:отреагировать{}, // отреагировать в прессе
rus_verbs:проверять{}, // проверять в аппарате
rus_verbs:убеждать{}, // убеждать в отсутствии альтернатив
rus_verbs:летать{}, // летать в комфортабельном частном самолёте
rus_verbs:толпиться{}, // толпиться в фойе
rus_verbs:плавать{}, // плавать в специальном костюме
rus_verbs:пробыть{}, // пробыть в воде слишком долго
rus_verbs:прикинуть{}, // прикинуть в уме
rus_verbs:застрять{}, // застрять в лифте
rus_verbs:метаться{}, // метаться в кровате
rus_verbs:сжечь{}, // сжечь в печке
rus_verbs:расслабиться{}, // расслабиться в ванной
rus_verbs:услыхать{}, // услыхать в автобусе
rus_verbs:удержать{}, // удержать в вертикальном положении
rus_verbs:образоваться{}, // образоваться в верхних слоях атмосферы
rus_verbs:рассмотреть{}, // рассмотреть в капле воды
rus_verbs:просмотреть{}, // просмотреть в браузере
rus_verbs:учесть{}, // учесть в планах
rus_verbs:уезжать{}, // уезжать в чьей-то машине
rus_verbs:похоронить{}, // похоронить в мерзлой земле
rus_verbs:растянуться{}, // растянуться в расслабленной позе
rus_verbs:обнаружиться{}, // обнаружиться в чужой сумке
rus_verbs:гулять{}, // гулять в парке
rus_verbs:утонуть{}, // утонуть в реке
rus_verbs:зажать{}, // зажать в медвежьих объятиях
rus_verbs:усомниться{}, // усомниться в объективности
rus_verbs:танцевать{}, // танцевать в спортзале
rus_verbs:проноситься{}, // проноситься в голове
rus_verbs:трудиться{}, // трудиться в кооперативе
глагол:засыпать{ aux stress="засып^ать" переходность:непереходный }, // засыпать в спальном мешке
инфинитив:засыпать{ aux stress="засып^ать" переходность:непереходный },
rus_verbs:сушить{}, // сушить в сушильном шкафу
rus_verbs:зашевелиться{}, // зашевелиться в траве
rus_verbs:обдумывать{}, // обдумывать в спокойной обстановке
rus_verbs:промелькнуть{}, // промелькнуть в окне
rus_verbs:поучаствовать{}, // поучаствовать в обсуждении
rus_verbs:закрыть{}, // закрыть в комнате
rus_verbs:запирать{}, // запирать в комнате
rus_verbs:закрывать{}, // закрывать в доме
rus_verbs:заблокировать{}, // заблокировать в доме
rus_verbs:зацвести{}, // В садах зацвела сирень
rus_verbs:кричать{}, // Какое-то животное кричало в ночном лесу.
rus_verbs:поглотить{}, // фотон, поглощенный в рецепторе
rus_verbs:стоять{}, // войска, стоявшие в Риме
rus_verbs:закалить{}, // ветераны, закаленные в боях
rus_verbs:выступать{}, // пришлось выступать в тюрьме.
rus_verbs:выступить{}, // пришлось выступить в тюрьме.
rus_verbs:закопошиться{}, // Мыши закопошились в траве
rus_verbs:воспламениться{}, // смесь, воспламенившаяся в цилиндре
rus_verbs:воспламеняться{}, // смесь, воспламеняющаяся в цилиндре
rus_verbs:закрываться{}, // закрываться в комнате
rus_verbs:провалиться{}, // провалиться в прокате
деепричастие:авторизируясь{ вид:несоверш },
глагол:авторизироваться{ вид:несоверш },
инфинитив:авторизироваться{ вид:несоверш }, // авторизироваться в системе
rus_verbs:существовать{}, // существовать в вакууме
деепричастие:находясь{},
прилагательное:находившийся{},
прилагательное:находящийся{},
глагол:находиться{ вид:несоверш },
инфинитив:находиться{ вид:несоверш }, // находиться в вакууме
rus_verbs:регистрировать{}, // регистрировать в инспекции
глагол:перерегистрировать{ вид:несоверш }, глагол:перерегистрировать{ вид:соверш },
инфинитив:перерегистрировать{ вид:несоверш }, инфинитив:перерегистрировать{ вид:соверш }, // перерегистрировать в инспекции
rus_verbs:поковыряться{}, // поковыряться в носу
rus_verbs:оттаять{}, // оттаять в кипятке
rus_verbs:распинаться{}, // распинаться в проклятиях
rus_verbs:отменить{}, // Министерство связи предлагает отменить внутренний роуминг в России
rus_verbs:столкнуться{}, // Американский эсминец и японский танкер столкнулись в Персидском заливе
rus_verbs:ценить{}, // Он очень ценил в статьях краткость изложения.
прилагательное:несчастный{}, // Он очень несчастен в семейной жизни.
rus_verbs:объясниться{}, // Он объяснился в любви.
прилагательное:нетвердый{}, // Он нетвёрд в истории.
rus_verbs:заниматься{}, // Он занимается в читальном зале.
rus_verbs:вращаться{}, // Он вращается в учёных кругах.
прилагательное:спокойный{}, // Он был спокоен и уверен в завтрашнем дне.
rus_verbs:бегать{}, // Он бегал по городу в поисках квартиры.
rus_verbs:заключать{}, // Письмо заключало в себе очень важные сведения.
rus_verbs:срабатывать{}, // Алгоритм срабатывает в половине случаев.
rus_verbs:специализироваться{}, // мы специализируемся в создании ядерного оружия
rus_verbs:сравниться{}, // Никто не может сравниться с ним в знаниях.
rus_verbs:продолжать{}, // Продолжайте в том же духе.
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:болтать{}, // Не болтай в присутствии начальника!
rus_verbs:проболтаться{}, // Не проболтайся в присутствии начальника!
rus_verbs:повторить{}, // Он должен повторить свои показания в присутствии свидетелей
rus_verbs:получить{}, // ректор поздравил студентов, получивших в этом семестре повышенную стипендию
rus_verbs:приобретать{}, // Эту еду мы приобретаем в соседнем магазине.
rus_verbs:расходиться{}, // Маша и Петя расходятся во взглядах
rus_verbs:сходиться{}, // Все дороги сходятся в Москве
rus_verbs:убирать{}, // убирать в комнате
rus_verbs:удостоверяться{}, // он удостоверяется в личности специалиста
rus_verbs:уединяться{}, // уединяться в пустыне
rus_verbs:уживаться{}, // уживаться в одном коллективе
rus_verbs:укорять{}, // укорять друга в забывчивости
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:состояться{}, // В Израиле состоятся досрочные парламентские выборы
rus_verbs:погибнуть{}, // Список погибших в авиакатастрофе под Ярославлем
rus_verbs:работать{}, // Я работаю в театре.
rus_verbs:признать{}, // Я признал в нём старого друга.
rus_verbs:преподавать{}, // Я преподаю в университете.
rus_verbs:понимать{}, // Я плохо понимаю в живописи.
rus_verbs:водиться{}, // неизвестный науке зверь, который водится в жарких тропических лесах
rus_verbs:разразиться{}, // В Москве разразилась эпидемия гриппа
rus_verbs:замереть{}, // вся толпа замерла в восхищении
rus_verbs:сидеть{}, // Я люблю сидеть в этом удобном кресле.
rus_verbs:идти{}, // Я иду в неопределённом направлении.
rus_verbs:заболеть{}, // Я заболел в дороге.
rus_verbs:ехать{}, // Я еду в автобусе
rus_verbs:взять{}, // Я взял книгу в библиотеке на неделю.
rus_verbs:провести{}, // Юные годы он провёл в Италии.
rus_verbs:вставать{}, // Этот случай живо встаёт в моей памяти.
rus_verbs:возвысить{}, // Это событие возвысило его в общественном мнении.
rus_verbs:произойти{}, // Это произошло в одном городе в Японии.
rus_verbs:привидеться{}, // Это мне привиделось во сне.
rus_verbs:держаться{}, // Это дело держится в большом секрете.
rus_verbs:привиться{}, // Это выражение не привилось в русском языке.
rus_verbs:восстановиться{}, // Эти писатели восстановились в правах.
rus_verbs:быть{}, // Эта книга есть в любом книжном магазине.
прилагательное:популярный{}, // Эта идея очень популярна в массах.
rus_verbs:шуметь{}, // Шумит в голове.
rus_verbs:остаться{}, // Шляпа осталась в поезде.
rus_verbs:выражаться{}, // Характер писателя лучше всего выражается в его произведениях.
rus_verbs:воспитать{}, // Учительница воспитала в детях любовь к природе.
rus_verbs:пересохнуть{}, // У меня в горле пересохло.
rus_verbs:щекотать{}, // У меня в горле щекочет.
rus_verbs:колоть{}, // У меня в боку колет.
прилагательное:свежий{}, // Событие ещё свежо в памяти.
rus_verbs:собрать{}, // Соберите всех учеников во дворе.
rus_verbs:белеть{}, // Снег белеет в горах.
rus_verbs:сделать{}, // Сколько орфографических ошибок ты сделал в диктанте?
rus_verbs:таять{}, // Сахар тает в кипятке.
rus_verbs:жать{}, // Сапог жмёт в подъёме.
rus_verbs:возиться{}, // Ребята возятся в углу.
rus_verbs:распоряжаться{}, // Прошу не распоряжаться в чужом доме.
rus_verbs:кружиться{}, // Они кружились в вальсе.
rus_verbs:выставлять{}, // Они выставляют его в смешном виде.
rus_verbs:бывать{}, // Она часто бывает в обществе.
rus_verbs:петь{}, // Она поёт в опере.
rus_verbs:сойтись{}, // Все свидетели сошлись в своих показаниях.
rus_verbs:валяться{}, // Вещи валялись в беспорядке.
rus_verbs:пройти{}, // Весь день прошёл в беготне.
rus_verbs:продавать{}, // В этом магазине продают обувь.
rus_verbs:заключаться{}, // В этом заключается вся сущность.
rus_verbs:звенеть{}, // В ушах звенит.
rus_verbs:проступить{}, // В тумане проступили очертания корабля.
rus_verbs:бить{}, // В саду бьёт фонтан.
rus_verbs:проскользнуть{}, // В речи проскользнул упрёк.
rus_verbs:оставить{}, // Не оставь товарища в опасности.
rus_verbs:прогулять{}, // Мы прогуляли час в парке.
rus_verbs:перебить{}, // Мы перебили врагов в бою.
rus_verbs:остановиться{}, // Мы остановились в первой попавшейся гостинице.
rus_verbs:видеть{}, // Он многое видел в жизни.
// глагол:проходить{ вид:несоверш }, // Беседа проходила в дружественной атмосфере.
rus_verbs:подать{}, // Автор подал своих героев в реалистических тонах.
rus_verbs:кинуть{}, // Он кинул меня в беде.
rus_verbs:приходить{}, // Приходи в сентябре
rus_verbs:воскрешать{}, // воскрешать в памяти
rus_verbs:соединять{}, // соединять в себе
rus_verbs:разбираться{}, // умение разбираться в вещах
rus_verbs:делать{}, // В её комнате делали обыск.
rus_verbs:воцариться{}, // В зале воцарилась глубокая тишина.
rus_verbs:начаться{}, // В деревне начались полевые работы.
rus_verbs:блеснуть{}, // В голове блеснула хорошая мысль.
rus_verbs:вертеться{}, // В голове вертится вчерашний разговор.
rus_verbs:веять{}, // В воздухе веет прохладой.
rus_verbs:висеть{}, // В воздухе висит зной.
rus_verbs:носиться{}, // В воздухе носятся комары.
rus_verbs:грести{}, // Грести в спокойной воде будет немного легче, но скучнее
rus_verbs:воскресить{}, // воскресить в памяти
rus_verbs:поплавать{}, // поплавать в 100-метровом бассейне
rus_verbs:пострадать{}, // В массовой драке пострадал 23-летний мужчина
прилагательное:уверенный{ причастие }, // Она уверена в своих силах.
прилагательное:постоянный{}, // Она постоянна во вкусах.
прилагательное:сильный{}, // Он не силён в математике.
прилагательное:повинный{}, // Он не повинен в этом.
прилагательное:возможный{}, // Ураганы, сильные грозы и даже смерчи возможны в конце периода сильной жары
rus_verbs:вывести{}, // способный летать над землей крокодил был выведен в секретной лаборатории
прилагательное:нужный{}, // сковородка тоже нужна в хозяйстве.
rus_verbs:сесть{}, // Она села в тени
rus_verbs:заливаться{}, // в нашем парке заливаются соловьи
rus_verbs:разнести{}, // В лесу огонь пожара мгновенно разнесло
rus_verbs:чувствоваться{}, // В тёплом, но сыром воздухе остро чувствовалось дыхание осени
// rus_verbs:расти{}, // дерево, растущее в лесу
rus_verbs:происходить{}, // что происходит в поликлиннике
rus_verbs:спать{}, // кто спит в моей кровати
rus_verbs:мыть{}, // мыть машину в саду
ГЛ_ИНФ(царить), // В воздухе царило безмолвие
ГЛ_ИНФ(мести), // мести в прихожей пол
ГЛ_ИНФ(прятать), // прятать в яме
ГЛ_ИНФ(увидеть), прилагательное:увидевший{}, деепричастие:увидев{}, // увидел периодическую таблицу элементов во сне.
// ГЛ_ИНФ(собраться), // собраться в порту
ГЛ_ИНФ(случиться), // что-то случилось в больнице
ГЛ_ИНФ(зажечься), // в небе зажглись звёзды
ГЛ_ИНФ(купить), // купи молока в магазине
прилагательное:пропагандировавшийся{} // группа студентов университета дружбы народов, активно пропагандировавшейся в СССР
}
// Чтобы разрешить связывание в паттернах типа: пообедать в macdonalds
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} *:*{ падеж:предл } }
then return true
}
// С локативом:
// собраться в порту
fact гл_предл
{
if context { Гл_В_Предл предлог:в{} существительное:*{ падеж:мест } }
then return true
}
#endregion Предложный
#region Винительный
// Для глаголов движения с выраженным направлением действия может присоединяться
// предложный паттерн с винительным падежом.
wordentry_set Гл_В_Вин =
{
rus_verbs:вдавиться{}, // Дуло больно вдавилось в позвонок.
глагол:ввергнуть{}, // Двух прелестнейших дам он ввергнул в горе.
глагол:ввергать{},
инфинитив:ввергнуть{},
инфинитив:ввергать{},
rus_verbs:двинуться{}, // Двинулись в путь и мы.
rus_verbs:сплавать{}, // Сплавать в Россию!
rus_verbs:уложиться{}, // Уложиться в воскресенье.
rus_verbs:спешить{}, // Спешите в Лондон
rus_verbs:кинуть{}, // Киньте в море.
rus_verbs:проситься{}, // Просилась в Никарагуа.
rus_verbs:притопать{}, // Притопал в Будапешт.
rus_verbs:скататься{}, // Скатался в Красноярск.
rus_verbs:соскользнуть{}, // Соскользнул в пике.
rus_verbs:соскальзывать{},
rus_verbs:играть{}, // Играл в дутье.
глагол:айда{}, // Айда в каморы.
rus_verbs:отзывать{}, // Отзывали в Москву...
rus_verbs:сообщаться{}, // Сообщается в Лондон.
rus_verbs:вдуматься{}, // Вдумайтесь в них.
rus_verbs:проехать{}, // Проехать в Лунево...
rus_verbs:спрыгивать{}, // Спрыгиваем в него.
rus_verbs:верить{}, // Верю в вас!
rus_verbs:прибыть{}, // Прибыл в Подмосковье.
rus_verbs:переходить{}, // Переходите в школу.
rus_verbs:доложить{}, // Доложили в Москву.
rus_verbs:подаваться{}, // Подаваться в Россию?
rus_verbs:спрыгнуть{}, // Спрыгнул в него.
rus_verbs:вывезти{}, // Вывезли в Китай.
rus_verbs:пропихивать{}, // Я очень аккуратно пропихивал дуло в ноздрю.
rus_verbs:пропихнуть{},
rus_verbs:транспортироваться{},
rus_verbs:закрадываться{}, // в голову начали закрадываться кое-какие сомнения и подозрения
rus_verbs:дуть{},
rus_verbs:БОГАТЕТЬ{}, //
rus_verbs:РАЗБОГАТЕТЬ{}, //
rus_verbs:ВОЗРАСТАТЬ{}, //
rus_verbs:ВОЗРАСТИ{}, //
rus_verbs:ПОДНЯТЬ{}, // Он поднял половинку самолета в воздух и на всей скорости повел ее к горам. (ПОДНЯТЬ)
rus_verbs:ОТКАТИТЬСЯ{}, // Услышав за спиной дыхание, он прыгнул вперед и откатился в сторону, рассчитывая ускользнуть от врага, нападавшего сзади (ОТКАТИТЬСЯ)
rus_verbs:ВПЛЕТАТЬСЯ{}, // В общий смрад вплеталось зловонье пены, летевшей из пастей, и крови из легких (ВПЛЕТАТЬСЯ)
rus_verbs:ЗАМАНИТЬ{}, // Они подумали, что Павел пытается заманить их в зону обстрела. (ЗАМАНИТЬ,ЗАМАНИВАТЬ)
rus_verbs:ЗАМАНИВАТЬ{},
rus_verbs:ПРОТРУБИТЬ{}, // Эти врата откроются, когда он протрубит в рог, и пропустят его в другую вселенную. (ПРОТРУБИТЬ)
rus_verbs:ВРУБИТЬСЯ{}, // Клинок сломался, не врубившись в металл. (ВРУБИТЬСЯ/ВРУБАТЬСЯ)
rus_verbs:ВРУБАТЬСЯ{},
rus_verbs:ОТПРАВИТЬ{}, // Мы ищем благородного вельможу, который нанял бы нас или отправил в рыцарский поиск. (ОТПРАВИТЬ)
rus_verbs:ОБЛАЧИТЬ{}, // Этот был облачен в сверкавшие красные доспехи с опущенным забралом и держал огромное копье, дожидаясь своей очереди. (ОБЛАЧИТЬ/ОБЛАЧАТЬ/ОБЛАЧИТЬСЯ/ОБЛАЧАТЬСЯ/НАРЯДИТЬСЯ/НАРЯЖАТЬСЯ)
rus_verbs:ОБЛАЧАТЬ{},
rus_verbs:ОБЛАЧИТЬСЯ{},
rus_verbs:ОБЛАЧАТЬСЯ{},
rus_verbs:НАРЯДИТЬСЯ{},
rus_verbs:НАРЯЖАТЬСЯ{},
rus_verbs:ЗАХВАТИТЬ{}, // Кроме набранного рабского материала обычного типа, он захватил в плен группу очень странных созданий, а также женщину исключительной красоты (ЗАХВАТИТЬ/ЗАХВАТЫВАТЬ/ЗАХВАТ)
rus_verbs:ЗАХВАТЫВАТЬ{},
rus_verbs:ПРОВЕСТИ{}, // Он провел их в маленькое святилище позади штурвала. (ПРОВЕСТИ)
rus_verbs:ПОЙМАТЬ{}, // Их можно поймать в ловушку (ПОЙМАТЬ)
rus_verbs:СТРОИТЬСЯ{}, // На вершине они остановились, строясь в круг. (СТРОИТЬСЯ,ПОСТРОИТЬСЯ,ВЫСТРОИТЬСЯ)
rus_verbs:ПОСТРОИТЬСЯ{},
rus_verbs:ВЫСТРОИТЬСЯ{},
rus_verbs:ВЫПУСТИТЬ{}, // Несколько стрел, выпущенных в преследуемых, вонзились в траву (ВЫПУСТИТЬ/ВЫПУСКАТЬ)
rus_verbs:ВЫПУСКАТЬ{},
rus_verbs:ВЦЕПЛЯТЬСЯ{}, // Они вцепляются тебе в горло. (ВЦЕПЛЯТЬСЯ/ВЦЕПИТЬСЯ)
rus_verbs:ВЦЕПИТЬСЯ{},
rus_verbs:ПАЛЬНУТЬ{}, // Вольф вставил в тетиву новую стрелу и пальнул в белое брюхо (ПАЛЬНУТЬ)
rus_verbs:ОТСТУПИТЬ{}, // Вольф отступил в щель. (ОТСТУПИТЬ/ОТСТУПАТЬ)
rus_verbs:ОТСТУПАТЬ{},
rus_verbs:КРИКНУТЬ{}, // Вольф крикнул в ответ и медленно отступил от птицы. (КРИКНУТЬ)
rus_verbs:ДЫХНУТЬ{}, // В лицо ему дыхнули винным перегаром. (ДЫХНУТЬ)
rus_verbs:ПОТРУБИТЬ{}, // Я видел рог во время своих скитаний по дворцу и даже потрубил в него (ПОТРУБИТЬ)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Некоторые врата открывались в другие вселенные (ОТКРЫВАТЬСЯ)
rus_verbs:ТРУБИТЬ{}, // А я трубил в рог (ТРУБИТЬ)
rus_verbs:ПЫРНУТЬ{}, // Вольф пырнул его в бок. (ПЫРНУТЬ)
rus_verbs:ПРОСКРЕЖЕТАТЬ{}, // Тот что-то проскрежетал в ответ, а затем наорал на него. (ПРОСКРЕЖЕТАТЬ В вин, НАОРАТЬ НА вин)
rus_verbs:ИМПОРТИРОВАТЬ{}, // импортировать товары двойного применения только в Российскую Федерацию (ИМПОРТИРОВАТЬ)
rus_verbs:ОТЪЕХАТЬ{}, // Легкий грохот катков заглушил рог, когда дверь отъехала в сторону. (ОТЪЕХАТЬ)
rus_verbs:ПОПЛЕСТИСЬ{}, // Подобрав нижнее белье, носки и ботинки, он поплелся по песку обратно в джунгли. (ПОПЛЕЛСЯ)
rus_verbs:СЖАТЬСЯ{}, // Желудок у него сжался в кулак. (СЖАТЬСЯ, СЖИМАТЬСЯ)
rus_verbs:СЖИМАТЬСЯ{},
rus_verbs:проверять{}, // Школьников будут принудительно проверять на курение
rus_verbs:ПОТЯНУТЬ{}, // Я потянул его в кино (ПОТЯНУТЬ)
rus_verbs:ПЕРЕВЕСТИ{}, // Премьер-министр Казахстана поручил до конца года перевести все социально-значимые услуги в электронный вид (ПЕРЕВЕСТИ)
rus_verbs:КРАСИТЬ{}, // Почему китайские партийные боссы красят волосы в черный цвет? (КРАСИТЬ/ПОКРАСИТЬ/ПЕРЕКРАСИТЬ/ОКРАСИТЬ/ЗАКРАСИТЬ)
rus_verbs:ПОКРАСИТЬ{}, //
rus_verbs:ПЕРЕКРАСИТЬ{}, //
rus_verbs:ОКРАСИТЬ{}, //
rus_verbs:ЗАКРАСИТЬ{}, //
rus_verbs:СООБЩИТЬ{}, // Мужчина ранил человека в щеку и сам сообщил об этом в полицию (СООБЩИТЬ)
rus_verbs:СТЯГИВАТЬ{}, // Но толщина пузыря постоянно меняется из-за гравитации, которая стягивает жидкость в нижнюю часть (СТЯГИВАТЬ/СТЯНУТЬ/ЗАТЯНУТЬ/ВТЯНУТЬ)
rus_verbs:СТЯНУТЬ{}, //
rus_verbs:ЗАТЯНУТЬ{}, //
rus_verbs:ВТЯНУТЬ{}, //
rus_verbs:СОХРАНИТЬ{}, // сохранить данные в файл (СОХРАНИТЬ)
деепричастие:придя{}, // Немного придя в себя
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:УЛЫБАТЬСЯ{}, // она улыбалась во весь рот (УЛЫБАТЬСЯ)
rus_verbs:МЕТНУТЬСЯ{}, // она метнулась обратно во тьму (МЕТНУТЬСЯ)
rus_verbs:ПОСЛЕДОВАТЬ{}, // большинство жителей города последовало за ним во дворец (ПОСЛЕДОВАТЬ)
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, // экстремисты перемещаются из лесов в Сеть (ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ВЫТАЩИТЬ{}, // Алексей позволил вытащить себя через дверь во тьму (ВЫТАЩИТЬ)
rus_verbs:СЫПАТЬСЯ{}, // внизу под ними камни градом сыпались во двор (СЫПАТЬСЯ)
rus_verbs:выезжать{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку
rus_verbs:КРИЧАТЬ{}, // ей хотелось кричать во весь голос (КРИЧАТЬ В вин)
rus_verbs:ВЫПРЯМИТЬСЯ{}, // волк выпрямился во весь огромный рост (ВЫПРЯМИТЬСЯ В вин)
rus_verbs:спрятать{}, // Джон спрятал очки во внутренний карман (спрятать в вин)
rus_verbs:ЭКСТРАДИРОВАТЬ{}, // Украина экстрадирует в Таджикистан задержанного бывшего премьер-министра (ЭКСТРАДИРОВАТЬ В вин)
rus_verbs:ВВОЗИТЬ{}, // лабораторный мониторинг ввозимой в Россию мясной продукции из США (ВВОЗИТЬ В вин)
rus_verbs:УПАКОВАТЬ{}, // упакованных в несколько слоев полиэтилена (УПАКОВАТЬ В вин)
rus_verbs:ОТТЯГИВАТЬ{}, // использовать естественную силу гравитации, оттягивая объекты в сторону и изменяя их орбиту (ОТТЯГИВАТЬ В вин)
rus_verbs:ПОЗВОНИТЬ{}, // они позвонили в отдел экологии городской администрации (ПОЗВОНИТЬ В)
rus_verbs:ПРИВЛЕЧЬ{}, // Открытость данных о лесе поможет привлечь инвестиции в отрасль (ПРИВЛЕЧЬ В)
rus_verbs:ЗАПРОСИТЬСЯ{}, // набегавшись и наплясавшись, Стасик утомился и запросился в кроватку (ЗАПРОСИТЬСЯ В)
rus_verbs:ОТСТАВИТЬ{}, // бутыль с ацетоном Витька отставил в сторонку (ОТСТАВИТЬ В)
rus_verbs:ИСПОЛЬЗОВАТЬ{}, // ты использовал свою магию во зло. (ИСПОЛЬЗОВАТЬ В вин)
rus_verbs:ВЫСЕВАТЬ{}, // В апреле редис возможно уже высевать в грунт (ВЫСЕВАТЬ В)
rus_verbs:ЗАГНАТЬ{}, // Американский психолог загнал любовь в три угла (ЗАГНАТЬ В)
rus_verbs:ЭВОЛЮЦИОНИРОВАТЬ{}, // Почему не все обезьяны эволюционировали в человека? (ЭВОЛЮЦИОНИРОВАТЬ В вин)
rus_verbs:СФОТОГРАФИРОВАТЬСЯ{}, // Он сфотографировался во весь рост. (СФОТОГРАФИРОВАТЬСЯ В)
rus_verbs:СТАВИТЬ{}, // Он ставит мне в упрёк свою ошибку. (СТАВИТЬ В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:ПЕРЕСЕЛЯТЬСЯ{}, // Греки переселяются в Германию (ПЕРЕСЕЛЯТЬСЯ В)
rus_verbs:ФОРМИРОВАТЬСЯ{}, // Сахарная свекла относится к двулетним растениям, мясистый корнеплод формируется в первый год. (ФОРМИРОВАТЬСЯ В)
rus_verbs:ПРОВОРЧАТЬ{}, // дедуля что-то проворчал в ответ (ПРОВОРЧАТЬ В)
rus_verbs:БУРКНУТЬ{}, // нелюдимый парень что-то буркнул в ответ (БУРКНУТЬ В)
rus_verbs:ВЕСТИ{}, // дверь вела во тьму. (ВЕСТИ В)
rus_verbs:ВЫСКОЧИТЬ{}, // беглецы выскочили во двор. (ВЫСКОЧИТЬ В)
rus_verbs:ДОСЫЛАТЬ{}, // Одним движением стрелок досылает патрон в ствол (ДОСЫЛАТЬ В)
rus_verbs:СЪЕХАТЬСЯ{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:ВЫТЯНУТЬ{}, // Дым вытянуло в трубу. (ВЫТЯНУТЬ В)
rus_verbs:торчать{}, // острые обломки бревен торчали во все стороны.
rus_verbs:ОГЛЯДЫВАТЬ{}, // Она оглядывает себя в зеркало. (ОГЛЯДЫВАТЬ В)
rus_verbs:ДЕЙСТВОВАТЬ{}, // Этот пакет законов действует в ущерб частным предпринимателям.
rus_verbs:РАЗЛЕТЕТЬСЯ{}, // люди разлетелись во все стороны. (РАЗЛЕТЕТЬСЯ В)
rus_verbs:брызнуть{}, // во все стороны брызнула кровь. (брызнуть в)
rus_verbs:ТЯНУТЬСЯ{}, // провода тянулись во все углы. (ТЯНУТЬСЯ В)
rus_verbs:валить{}, // валить все в одну кучу (валить в)
rus_verbs:выдвинуть{}, // его выдвинули в палату представителей (выдвинуть в)
rus_verbs:карабкаться{}, // карабкаться в гору (карабкаться в)
rus_verbs:клониться{}, // он клонился в сторону (клониться в)
rus_verbs:командировать{}, // мы командировали нашего представителя в Рим (командировать в)
rus_verbs:запасть{}, // Эти слова запали мне в душу.
rus_verbs:давать{}, // В этой лавке дают в долг?
rus_verbs:ездить{}, // Каждый день грузовик ездит в город.
rus_verbs:претвориться{}, // Замысел претворился в жизнь.
rus_verbs:разойтись{}, // Они разошлись в разные стороны.
rus_verbs:выйти{}, // Охотник вышел в поле с ружьём.
rus_verbs:отозвать{}, // Отзовите его в сторону и скажите ему об этом.
rus_verbs:расходиться{}, // Маша и Петя расходятся в разные стороны
rus_verbs:переодеваться{}, // переодеваться в женское платье
rus_verbs:перерастать{}, // перерастать в массовые беспорядки
rus_verbs:завязываться{}, // завязываться в узел
rus_verbs:похватать{}, // похватать в руки
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:помещать{}, // помещать в изолятор
rus_verbs:зыркнуть{}, // зыркнуть в окошко
rus_verbs:закатать{}, // закатать в асфальт
rus_verbs:усаживаться{}, // усаживаться в кресло
rus_verbs:загонять{}, // загонять в сарай
rus_verbs:подбрасывать{}, // подбрасывать в воздух
rus_verbs:телеграфировать{}, // телеграфировать в центр
rus_verbs:вязать{}, // вязать в стопы
rus_verbs:подлить{}, // подлить в огонь
rus_verbs:заполучить{}, // заполучить в распоряжение
rus_verbs:подогнать{}, // подогнать в док
rus_verbs:ломиться{}, // ломиться в открытую дверь
rus_verbs:переправить{}, // переправить в деревню
rus_verbs:затягиваться{}, // затягиваться в трубу
rus_verbs:разлетаться{}, // разлетаться в стороны
rus_verbs:кланяться{}, // кланяться в ножки
rus_verbs:устремляться{}, // устремляться в открытое море
rus_verbs:переместиться{}, // переместиться в другую аудиторию
rus_verbs:ложить{}, // ложить в ящик
rus_verbs:отвозить{}, // отвозить в аэропорт
rus_verbs:напрашиваться{}, // напрашиваться в гости
rus_verbs:напроситься{}, // напроситься в гости
rus_verbs:нагрянуть{}, // нагрянуть в гости
rus_verbs:заворачивать{}, // заворачивать в фольгу
rus_verbs:заковать{}, // заковать в кандалы
rus_verbs:свезти{}, // свезти в сарай
rus_verbs:притащиться{}, // притащиться в дом
rus_verbs:завербовать{}, // завербовать в разведку
rus_verbs:рубиться{}, // рубиться в компьютерные игры
rus_verbs:тыкаться{}, // тыкаться в материнскую грудь
инфинитив:ссыпать{ вид:несоверш }, инфинитив:ссыпать{ вид:соверш }, // ссыпать в контейнер
глагол:ссыпать{ вид:несоверш }, глагол:ссыпать{ вид:соверш },
деепричастие:ссыпав{}, деепричастие:ссыпая{},
rus_verbs:засасывать{}, // засасывать в себя
rus_verbs:скакнуть{}, // скакнуть в будущее
rus_verbs:подвозить{}, // подвозить в театр
rus_verbs:переиграть{}, // переиграть в покер
rus_verbs:мобилизовать{}, // мобилизовать в действующую армию
rus_verbs:залетать{}, // залетать в закрытое воздушное пространство
rus_verbs:подышать{}, // подышать в трубочку
rus_verbs:смотаться{}, // смотаться в институт
rus_verbs:рассовать{}, // рассовать в кармашки
rus_verbs:захаживать{}, // захаживать в дом
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять в ломбард
деепричастие:сгоняя{},
rus_verbs:посылаться{}, // посылаться в порт
rus_verbs:отлить{}, // отлить в кастрюлю
rus_verbs:преобразоваться{}, // преобразоваться в линейное уравнение
rus_verbs:поплакать{}, // поплакать в платочек
rus_verbs:обуться{}, // обуться в сапоги
rus_verbs:закапать{}, // закапать в глаза
инфинитив:свозить{ вид:несоверш }, инфинитив:свозить{ вид:соверш }, // свозить в центр утилизации
глагол:свозить{ вид:несоверш }, глагол:свозить{ вид:соверш },
деепричастие:свозив{}, деепричастие:свозя{},
rus_verbs:преобразовать{}, // преобразовать в линейное уравнение
rus_verbs:кутаться{}, // кутаться в плед
rus_verbs:смещаться{}, // смещаться в сторону
rus_verbs:зазывать{}, // зазывать в свой магазин
инфинитив:трансформироваться{ вид:несоверш }, инфинитив:трансформироваться{ вид:соверш }, // трансформироваться в комбинезон
глагол:трансформироваться{ вид:несоверш }, глагол:трансформироваться{ вид:соверш },
деепричастие:трансформируясь{}, деепричастие:трансформировавшись{},
rus_verbs:погружать{}, // погружать в кипящее масло
rus_verbs:обыграть{}, // обыграть в теннис
rus_verbs:закутать{}, // закутать в одеяло
rus_verbs:изливаться{}, // изливаться в воду
rus_verbs:закатывать{}, // закатывать в асфальт
rus_verbs:мотнуться{}, // мотнуться в банк
rus_verbs:избираться{}, // избираться в сенат
rus_verbs:наниматься{}, // наниматься в услужение
rus_verbs:настучать{}, // настучать в органы
rus_verbs:запихивать{}, // запихивать в печку
rus_verbs:закапывать{}, // закапывать в нос
rus_verbs:засобираться{}, // засобираться в поход
rus_verbs:копировать{}, // копировать в другую папку
rus_verbs:замуровать{}, // замуровать в стену
rus_verbs:упечь{}, // упечь в тюрьму
rus_verbs:зрить{}, // зрить в корень
rus_verbs:стягиваться{}, // стягиваться в одну точку
rus_verbs:усаживать{}, // усаживать в тренажер
rus_verbs:протолкнуть{}, // протолкнуть в отверстие
rus_verbs:расшибиться{}, // расшибиться в лепешку
rus_verbs:приглашаться{}, // приглашаться в кабинет
rus_verbs:садить{}, // садить в телегу
rus_verbs:уткнуть{}, // уткнуть в подушку
rus_verbs:протечь{}, // протечь в подвал
rus_verbs:перегнать{}, // перегнать в другую страну
rus_verbs:переползти{}, // переползти в тень
rus_verbs:зарываться{}, // зарываться в грунт
rus_verbs:переодеть{}, // переодеть в сухую одежду
rus_verbs:припуститься{}, // припуститься в пляс
rus_verbs:лопотать{}, // лопотать в микрофон
rus_verbs:прогнусавить{}, // прогнусавить в микрофон
rus_verbs:мочиться{}, // мочиться в штаны
rus_verbs:загружать{}, // загружать в патронник
rus_verbs:радировать{}, // радировать в центр
rus_verbs:промотать{}, // промотать в конец
rus_verbs:помчать{}, // помчать в школу
rus_verbs:съезжать{}, // съезжать в кювет
rus_verbs:завозить{}, // завозить в магазин
rus_verbs:заявляться{}, // заявляться в школу
rus_verbs:наглядеться{}, // наглядеться в зеркало
rus_verbs:сворачиваться{}, // сворачиваться в клубочек
rus_verbs:устремлять{}, // устремлять взор в будущее
rus_verbs:забредать{}, // забредать в глухие уголки
rus_verbs:перемотать{}, // перемотать в самое начало диалога
rus_verbs:сморкаться{}, // сморкаться в носовой платочек
rus_verbs:перетекать{}, // перетекать в другой сосуд
rus_verbs:закачать{}, // закачать в шарик
rus_verbs:запрятать{}, // запрятать в сейф
rus_verbs:пинать{}, // пинать в живот
rus_verbs:затрубить{}, // затрубить в горн
rus_verbs:подглядывать{}, // подглядывать в замочную скважину
инфинитив:подсыпать{ вид:соверш }, инфинитив:подсыпать{ вид:несоверш }, // подсыпать в питье
глагол:подсыпать{ вид:соверш }, глагол:подсыпать{ вид:несоверш },
деепричастие:подсыпав{}, деепричастие:подсыпая{},
rus_verbs:засовывать{}, // засовывать в пенал
rus_verbs:отрядить{}, // отрядить в командировку
rus_verbs:справлять{}, // справлять в кусты
rus_verbs:поторапливаться{}, // поторапливаться в самолет
rus_verbs:скопировать{}, // скопировать в кэш
rus_verbs:подливать{}, // подливать в огонь
rus_verbs:запрячь{}, // запрячь в повозку
rus_verbs:окраситься{}, // окраситься в пурпур
rus_verbs:уколоть{}, // уколоть в шею
rus_verbs:слететься{}, // слететься в гнездо
rus_verbs:резаться{}, // резаться в карты
rus_verbs:затесаться{}, // затесаться в ряды оппозиционеров
инфинитив:задвигать{ вид:несоверш }, глагол:задвигать{ вид:несоверш }, // задвигать в ячейку (несоверш)
деепричастие:задвигая{},
rus_verbs:доставляться{}, // доставляться в ресторан
rus_verbs:поплевать{}, // поплевать в чашку
rus_verbs:попереться{}, // попереться в магазин
rus_verbs:хаживать{}, // хаживать в церковь
rus_verbs:преображаться{}, // преображаться в королеву
rus_verbs:организоваться{}, // организоваться в группу
rus_verbs:ужалить{}, // ужалить в руку
rus_verbs:протискиваться{}, // протискиваться в аудиторию
rus_verbs:препроводить{}, // препроводить в закуток
rus_verbs:разъезжаться{}, // разъезжаться в разные стороны
rus_verbs:пропыхтеть{}, // пропыхтеть в трубку
rus_verbs:уволочь{}, // уволочь в нору
rus_verbs:отодвигаться{}, // отодвигаться в сторону
rus_verbs:разливать{}, // разливать в стаканы
rus_verbs:сбегаться{}, // сбегаться в актовый зал
rus_verbs:наведаться{}, // наведаться в кладовку
rus_verbs:перекочевать{}, // перекочевать в горы
rus_verbs:прощебетать{}, // прощебетать в трубку
rus_verbs:перекладывать{}, // перекладывать в другой карман
rus_verbs:углубляться{}, // углубляться в теорию
rus_verbs:переименовать{}, // переименовать в город
rus_verbs:переметнуться{}, // переметнуться в лагерь противника
rus_verbs:разносить{}, // разносить в щепки
rus_verbs:осыпаться{}, // осыпаться в холода
rus_verbs:попроситься{}, // попроситься в туалет
rus_verbs:уязвить{}, // уязвить в сердце
rus_verbs:перетащить{}, // перетащить в дом
rus_verbs:закутаться{}, // закутаться в плед
// rus_verbs:упаковать{}, // упаковать в бумагу
инфинитив:тикать{ aux stress="тик^ать" }, глагол:тикать{ aux stress="тик^ать" }, // тикать в крепость
rus_verbs:хихикать{}, // хихикать в кулачок
rus_verbs:объединить{}, // объединить в сеть
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать в Калифорнию
деепричастие:слетав{},
rus_verbs:заползти{}, // заползти в норку
rus_verbs:перерасти{}, // перерасти в крупную аферу
rus_verbs:списать{}, // списать в утиль
rus_verbs:просачиваться{}, // просачиваться в бункер
rus_verbs:пускаться{}, // пускаться в погоню
rus_verbs:согревать{}, // согревать в мороз
rus_verbs:наливаться{}, // наливаться в емкость
rus_verbs:унестись{}, // унестись в небо
rus_verbs:зашвырнуть{}, // зашвырнуть в шкаф
rus_verbs:сигануть{}, // сигануть в воду
rus_verbs:окунуть{}, // окунуть в ледяную воду
rus_verbs:просочиться{}, // просочиться в сапог
rus_verbs:соваться{}, // соваться в толпу
rus_verbs:протолкаться{}, // протолкаться в гардероб
rus_verbs:заложить{}, // заложить в ломбард
rus_verbs:перекатить{}, // перекатить в сарай
rus_verbs:поставлять{}, // поставлять в Китай
rus_verbs:залезать{}, // залезать в долги
rus_verbs:отлучаться{}, // отлучаться в туалет
rus_verbs:сбиваться{}, // сбиваться в кучу
rus_verbs:зарыть{}, // зарыть в землю
rus_verbs:засадить{}, // засадить в тело
rus_verbs:прошмыгнуть{}, // прошмыгнуть в дверь
rus_verbs:переставить{}, // переставить в шкаф
rus_verbs:отчалить{}, // отчалить в плавание
rus_verbs:набираться{}, // набираться в команду
rus_verbs:лягнуть{}, // лягнуть в живот
rus_verbs:притворить{}, // притворить в жизнь
rus_verbs:проковылять{}, // проковылять в гардероб
rus_verbs:прикатить{}, // прикатить в гараж
rus_verbs:залететь{}, // залететь в окно
rus_verbs:переделать{}, // переделать в мопед
rus_verbs:протащить{}, // протащить в совет
rus_verbs:обмакнуть{}, // обмакнуть в воду
rus_verbs:отклоняться{}, // отклоняться в сторону
rus_verbs:запихать{}, // запихать в пакет
rus_verbs:избирать{}, // избирать в совет
rus_verbs:загрузить{}, // загрузить в буфер
rus_verbs:уплывать{}, // уплывать в Париж
rus_verbs:забивать{}, // забивать в мерзлоту
rus_verbs:потыкать{}, // потыкать в безжизненную тушу
rus_verbs:съезжаться{}, // съезжаться в санаторий
rus_verbs:залепить{}, // залепить в рыло
rus_verbs:набиться{}, // набиться в карманы
rus_verbs:уползти{}, // уползти в нору
rus_verbs:упрятать{}, // упрятать в камеру
rus_verbs:переместить{}, // переместить в камеру анабиоза
rus_verbs:закрасться{}, // закрасться в душу
rus_verbs:сместиться{}, // сместиться в инфракрасную область
rus_verbs:запускать{}, // запускать в серию
rus_verbs:потрусить{}, // потрусить в чащобу
rus_verbs:забрасывать{}, // забрасывать в чистую воду
rus_verbs:переселить{}, // переселить в отдаленную деревню
rus_verbs:переезжать{}, // переезжать в новую квартиру
rus_verbs:приподнимать{}, // приподнимать в воздух
rus_verbs:добавиться{}, // добавиться в конец очереди
rus_verbs:убыть{}, // убыть в часть
rus_verbs:передвигать{}, // передвигать в соседнюю клетку
rus_verbs:добавляться{}, // добавляться в очередь
rus_verbs:дописать{}, // дописать в перечень
rus_verbs:записываться{}, // записываться в кружок
rus_verbs:продаться{}, // продаться в кредитное рабство
rus_verbs:переписывать{}, // переписывать в тетрадку
rus_verbs:заплыть{}, // заплыть в территориальные воды
инфинитив:пописать{ aux stress="поп^исать" }, инфинитив:пописать{ aux stress="попис^ать" }, // пописать в горшок
глагол:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="попис^ать" },
rus_verbs:отбирать{}, // отбирать в гвардию
rus_verbs:нашептывать{}, // нашептывать в микрофон
rus_verbs:ковылять{}, // ковылять в стойло
rus_verbs:прилетать{}, // прилетать в Париж
rus_verbs:пролиться{}, // пролиться в канализацию
rus_verbs:запищать{}, // запищать в микрофон
rus_verbs:подвезти{}, // подвезти в больницу
rus_verbs:припереться{}, // припереться в театр
rus_verbs:утечь{}, // утечь в сеть
rus_verbs:прорываться{}, // прорываться в буфет
rus_verbs:увозить{}, // увозить в ремонт
rus_verbs:съедать{}, // съедать в обед
rus_verbs:просунуться{}, // просунуться в дверь
rus_verbs:перенестись{}, // перенестись в прошлое
rus_verbs:завезти{}, // завезти в магазин
rus_verbs:проложить{}, // проложить в деревню
rus_verbs:объединяться{}, // объединяться в профсоюз
rus_verbs:развиться{}, // развиться в бабочку
rus_verbs:засеменить{}, // засеменить в кабинку
rus_verbs:скатываться{}, // скатываться в яму
rus_verbs:завозиться{}, // завозиться в магазин
rus_verbs:нанимать{}, // нанимать в рейс
rus_verbs:поспеть{}, // поспеть в класс
rus_verbs:кидаться{}, // кинаться в крайности
rus_verbs:поспевать{}, // поспевать в оперу
rus_verbs:обернуть{}, // обернуть в фольгу
rus_verbs:обратиться{}, // обратиться в прокуратуру
rus_verbs:истолковать{}, // истолковать в свою пользу
rus_verbs:таращиться{}, // таращиться в дисплей
rus_verbs:прыснуть{}, // прыснуть в кулачок
rus_verbs:загнуть{}, // загнуть в другую сторону
rus_verbs:раздать{}, // раздать в разные руки
rus_verbs:назначить{}, // назначить в приемную комиссию
rus_verbs:кидать{}, // кидать в кусты
rus_verbs:увлекать{}, // увлекать в лес
rus_verbs:переселиться{}, // переселиться в чужое тело
rus_verbs:присылать{}, // присылать в город
rus_verbs:уплыть{}, // уплыть в Европу
rus_verbs:запричитать{}, // запричитать в полный голос
rus_verbs:утащить{}, // утащить в логово
rus_verbs:завернуться{}, // завернуться в плед
rus_verbs:заносить{}, // заносить в блокнот
rus_verbs:пятиться{}, // пятиться в дом
rus_verbs:наведываться{}, // наведываться в больницу
rus_verbs:нырять{}, // нырять в прорубь
rus_verbs:зачастить{}, // зачастить в бар
rus_verbs:назначаться{}, // назначается в комиссию
rus_verbs:мотаться{}, // мотаться в областной центр
rus_verbs:разыграть{}, // разыграть в карты
rus_verbs:пропищать{}, // пропищать в микрофон
rus_verbs:пихнуть{}, // пихнуть в бок
rus_verbs:эмигрировать{}, // эмигрировать в Канаду
rus_verbs:подключить{}, // подключить в сеть
rus_verbs:упереть{}, // упереть в фундамент
rus_verbs:уплатить{}, // уплатить в кассу
rus_verbs:потащиться{}, // потащиться в медпункт
rus_verbs:пригнать{}, // пригнать в стойло
rus_verbs:оттеснить{}, // оттеснить в фойе
rus_verbs:стучаться{}, // стучаться в ворота
rus_verbs:перечислить{}, // перечислить в фонд
rus_verbs:сомкнуть{}, // сомкнуть в круг
rus_verbs:закачаться{}, // закачаться в резервуар
rus_verbs:кольнуть{}, // кольнуть в бок
rus_verbs:накрениться{}, // накрениться в сторону берега
rus_verbs:подвинуться{}, // подвинуться в другую сторону
rus_verbs:разнести{}, // разнести в клочья
rus_verbs:отливать{}, // отливать в форму
rus_verbs:подкинуть{}, // подкинуть в карман
rus_verbs:уводить{}, // уводить в кабинет
rus_verbs:ускакать{}, // ускакать в школу
rus_verbs:ударять{}, // ударять в барабаны
rus_verbs:даться{}, // даться в руки
rus_verbs:поцеловаться{}, // поцеловаться в губы
rus_verbs:посветить{}, // посветить в подвал
rus_verbs:тыкать{}, // тыкать в арбуз
rus_verbs:соединяться{}, // соединяться в кольцо
rus_verbs:растянуть{}, // растянуть в тонкую ниточку
rus_verbs:побросать{}, // побросать в пыль
rus_verbs:стукнуться{}, // стукнуться в закрытую дверь
rus_verbs:проигрывать{}, // проигрывать в теннис
rus_verbs:дунуть{}, // дунуть в трубочку
rus_verbs:улетать{}, // улетать в Париж
rus_verbs:переводиться{}, // переводиться в филиал
rus_verbs:окунуться{}, // окунуться в водоворот событий
rus_verbs:попрятаться{}, // попрятаться в норы
rus_verbs:перевезти{}, // перевезти в соседнюю палату
rus_verbs:топать{}, // топать в школу
rus_verbs:относить{}, // относить в помещение
rus_verbs:укладывать{}, // укладывать в стопку
rus_verbs:укатить{}, // укатил в турне
rus_verbs:убирать{}, // убирать в сумку
rus_verbs:помалкивать{}, // помалкивать в тряпочку
rus_verbs:ронять{}, // ронять в грязь
rus_verbs:глазеть{}, // глазеть в бинокль
rus_verbs:преобразиться{}, // преобразиться в другого человека
rus_verbs:запрыгнуть{}, // запрыгнуть в поезд
rus_verbs:сгодиться{}, // сгодиться в суп
rus_verbs:проползти{}, // проползти в нору
rus_verbs:забираться{}, // забираться в коляску
rus_verbs:сбежаться{}, // сбежались в класс
rus_verbs:закатиться{}, // закатиться в угол
rus_verbs:плевать{}, // плевать в душу
rus_verbs:поиграть{}, // поиграть в демократию
rus_verbs:кануть{}, // кануть в небытие
rus_verbs:опаздывать{}, // опаздывать в школу
rus_verbs:отползти{}, // отползти в сторону
rus_verbs:стекаться{}, // стекаться в отстойник
rus_verbs:запихнуть{}, // запихнуть в пакет
rus_verbs:вышвырнуть{}, // вышвырнуть в коридор
rus_verbs:связываться{}, // связываться в плотный узел
rus_verbs:затолкать{}, // затолкать в ухо
rus_verbs:скрутить{}, // скрутить в трубочку
rus_verbs:сворачивать{}, // сворачивать в трубочку
rus_verbs:сплестись{}, // сплестись в узел
rus_verbs:заскочить{}, // заскочить в кабинет
rus_verbs:проваливаться{}, // проваливаться в сон
rus_verbs:уверовать{}, // уверовать в свою безнаказанность
rus_verbs:переписать{}, // переписать в тетрадку
rus_verbs:переноситься{}, // переноситься в мир фантазий
rus_verbs:заводить{}, // заводить в помещение
rus_verbs:сунуться{}, // сунуться в аудиторию
rus_verbs:устраиваться{}, // устраиваться в автомастерскую
rus_verbs:пропускать{}, // пропускать в зал
инфинитив:сбегать{ вид:несоверш }, инфинитив:сбегать{ вид:соверш }, // сбегать в кино
глагол:сбегать{ вид:несоверш }, глагол:сбегать{ вид:соверш },
деепричастие:сбегая{}, деепричастие:сбегав{},
rus_verbs:прибегать{}, // прибегать в школу
rus_verbs:съездить{}, // съездить в лес
rus_verbs:захлопать{}, // захлопать в ладошки
rus_verbs:опрокинуться{}, // опрокинуться в грязь
инфинитив:насыпать{ вид:несоверш }, инфинитив:насыпать{ вид:соверш }, // насыпать в стакан
глагол:насыпать{ вид:несоверш }, глагол:насыпать{ вид:соверш },
деепричастие:насыпая{}, деепричастие:насыпав{},
rus_verbs:употреблять{}, // употреблять в пищу
rus_verbs:приводиться{}, // приводиться в действие
rus_verbs:пристроить{}, // пристроить в надежные руки
rus_verbs:юркнуть{}, // юркнуть в нору
rus_verbs:объединиться{}, // объединиться в банду
rus_verbs:сажать{}, // сажать в одиночку
rus_verbs:соединить{}, // соединить в кольцо
rus_verbs:забрести{}, // забрести в кафешку
rus_verbs:свернуться{}, // свернуться в клубочек
rus_verbs:пересесть{}, // пересесть в другой автобус
rus_verbs:постучаться{}, // постучаться в дверцу
rus_verbs:соединять{}, // соединять в кольцо
rus_verbs:приволочь{}, // приволочь в коморку
rus_verbs:смахивать{}, // смахивать в ящик стола
rus_verbs:забежать{}, // забежать в помещение
rus_verbs:целиться{}, // целиться в беглеца
rus_verbs:прокрасться{}, // прокрасться в хранилище
rus_verbs:заковылять{}, // заковылять в травтамологию
rus_verbs:прискакать{}, // прискакать в стойло
rus_verbs:колотить{}, // колотить в дверь
rus_verbs:смотреться{}, // смотреться в зеркало
rus_verbs:подложить{}, // подложить в салон
rus_verbs:пущать{}, // пущать в королевские покои
rus_verbs:согнуть{}, // согнуть в дугу
rus_verbs:забарабанить{}, // забарабанить в дверь
rus_verbs:отклонить{}, // отклонить в сторону посадочной полосы
rus_verbs:убраться{}, // убраться в специальную нишу
rus_verbs:насмотреться{}, // насмотреться в зеркало
rus_verbs:чмокнуть{}, // чмокнуть в щечку
rus_verbs:усмехаться{}, // усмехаться в бороду
rus_verbs:передвинуть{}, // передвинуть в конец очереди
rus_verbs:допускаться{}, // допускаться в опочивальню
rus_verbs:задвинуть{}, // задвинуть в дальний угол
rus_verbs:отправлять{}, // отправлять в центр
rus_verbs:сбрасывать{}, // сбрасывать в жерло
rus_verbs:расстреливать{}, // расстреливать в момент обнаружения
rus_verbs:заволочь{}, // заволочь в закуток
rus_verbs:пролить{}, // пролить в воду
rus_verbs:зарыться{}, // зарыться в сено
rus_verbs:переливаться{}, // переливаться в емкость
rus_verbs:затащить{}, // затащить в клуб
rus_verbs:перебежать{}, // перебежать в лагерь врагов
rus_verbs:одеть{}, // одеть в новое платье
инфинитив:задвигаться{ вид:несоверш }, глагол:задвигаться{ вид:несоверш }, // задвигаться в нишу
деепричастие:задвигаясь{},
rus_verbs:клюнуть{}, // клюнуть в темечко
rus_verbs:наливать{}, // наливать в кружку
rus_verbs:пролезть{}, // пролезть в ушко
rus_verbs:откладывать{}, // откладывать в ящик
rus_verbs:протянуться{}, // протянуться в соседний дом
rus_verbs:шлепнуться{}, // шлепнуться лицом в грязь
rus_verbs:устанавливать{}, // устанавливать в машину
rus_verbs:употребляться{}, // употребляться в пищу
rus_verbs:переключиться{}, // переключиться в реверсный режим
rus_verbs:пискнуть{}, // пискнуть в микрофон
rus_verbs:заявиться{}, // заявиться в класс
rus_verbs:налиться{}, // налиться в стакан
rus_verbs:заливать{}, // заливать в бак
rus_verbs:ставиться{}, // ставиться в очередь
инфинитив:писаться{ aux stress="п^исаться" }, глагол:писаться{ aux stress="п^исаться" }, // писаться в штаны
деепричастие:писаясь{},
rus_verbs:целоваться{}, // целоваться в губы
rus_verbs:наносить{}, // наносить в область сердца
rus_verbs:посмеяться{}, // посмеяться в кулачок
rus_verbs:употребить{}, // употребить в пищу
rus_verbs:прорваться{}, // прорваться в столовую
rus_verbs:укладываться{}, // укладываться в ровные стопки
rus_verbs:пробиться{}, // пробиться в финал
rus_verbs:забить{}, // забить в землю
rus_verbs:переложить{}, // переложить в другой карман
rus_verbs:опускать{}, // опускать в свежевырытую могилу
rus_verbs:поторопиться{}, // поторопиться в школу
rus_verbs:сдвинуться{}, // сдвинуться в сторону
rus_verbs:капать{}, // капать в смесь
rus_verbs:погружаться{}, // погружаться во тьму
rus_verbs:направлять{}, // направлять в кабинку
rus_verbs:погрузить{}, // погрузить во тьму
rus_verbs:примчаться{}, // примчаться в школу
rus_verbs:упираться{}, // упираться в дверь
rus_verbs:удаляться{}, // удаляться в комнату совещаний
rus_verbs:ткнуться{}, // ткнуться в окошко
rus_verbs:убегать{}, // убегать в чащу
rus_verbs:соединиться{}, // соединиться в необычную пространственную фигуру
rus_verbs:наговорить{}, // наговорить в микрофон
rus_verbs:переносить{}, // переносить в дом
rus_verbs:прилечь{}, // прилечь в кроватку
rus_verbs:поворачивать{}, // поворачивать в обратную сторону
rus_verbs:проскочить{}, // проскочить в щель
rus_verbs:совать{}, // совать в духовку
rus_verbs:переодеться{}, // переодеться в чистую одежду
rus_verbs:порвать{}, // порвать в лоскуты
rus_verbs:завязать{}, // завязать в бараний рог
rus_verbs:съехать{}, // съехать в кювет
rus_verbs:литься{}, // литься в канистру
rus_verbs:уклониться{}, // уклониться в левую сторону
rus_verbs:смахнуть{}, // смахнуть в мусорное ведро
rus_verbs:спускать{}, // спускать в шахту
rus_verbs:плеснуть{}, // плеснуть в воду
rus_verbs:подуть{}, // подуть в угольки
rus_verbs:набирать{}, // набирать в команду
rus_verbs:хлопать{}, // хлопать в ладошки
rus_verbs:ранить{}, // ранить в самое сердце
rus_verbs:посматривать{}, // посматривать в иллюминатор
rus_verbs:превращать{}, // превращать воду в вино
rus_verbs:толкать{}, // толкать в пучину
rus_verbs:отбыть{}, // отбыть в расположение части
rus_verbs:сгрести{}, // сгрести в карман
rus_verbs:удрать{}, // удрать в тайгу
rus_verbs:пристроиться{}, // пристроиться в хорошую фирму
rus_verbs:сбиться{}, // сбиться в плотную группу
rus_verbs:заключать{}, // заключать в объятия
rus_verbs:отпускать{}, // отпускать в поход
rus_verbs:устремить{}, // устремить взгляд в будущее
rus_verbs:обронить{}, // обронить в траву
rus_verbs:сливаться{}, // сливаться в речку
rus_verbs:стекать{}, // стекать в канаву
rus_verbs:свалить{}, // свалить в кучу
rus_verbs:подтянуть{}, // подтянуть в кабину
rus_verbs:скатиться{}, // скатиться в канаву
rus_verbs:проскользнуть{}, // проскользнуть в приоткрытую дверь
rus_verbs:заторопиться{}, // заторопиться в буфет
rus_verbs:протиснуться{}, // протиснуться в центр толпы
rus_verbs:прятать{}, // прятать в укромненькое местечко
rus_verbs:пропеть{}, // пропеть в микрофон
rus_verbs:углубиться{}, // углубиться в джунгли
rus_verbs:сползти{}, // сползти в яму
rus_verbs:записывать{}, // записывать в память
rus_verbs:расстрелять{}, // расстрелять в упор (наречный оборот В УПОР)
rus_verbs:колотиться{}, // колотиться в дверь
rus_verbs:просунуть{}, // просунуть в отверстие
rus_verbs:провожать{}, // провожать в армию
rus_verbs:катить{}, // катить в гараж
rus_verbs:поражать{}, // поражать в самое сердце
rus_verbs:отлететь{}, // отлететь в дальний угол
rus_verbs:закинуть{}, // закинуть в речку
rus_verbs:катиться{}, // катиться в пропасть
rus_verbs:забросить{}, // забросить в дальний угол
rus_verbs:отвезти{}, // отвезти в лагерь
rus_verbs:втопить{}, // втопить педаль в пол
rus_verbs:втапливать{}, // втапливать педать в пол
rus_verbs:утопить{}, // утопить кнопку в панель
rus_verbs:напасть{}, // В Пекине участники антияпонских протестов напали на машину посла США
rus_verbs:нанять{}, // Босс нанял в службу поддержки еще несколько девушек
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:баллотировать{}, // претендент был баллотирован в жюри (баллотирован?)
rus_verbs:вбухать{}, // Власти вбухали в этой проект много денег
rus_verbs:вбухивать{}, // Власти вбухивают в этот проект очень много денег
rus_verbs:поскакать{}, // поскакать в атаку
rus_verbs:прицелиться{}, // прицелиться в бегущего зайца
rus_verbs:прыгать{}, // прыгать в кровать
rus_verbs:приглашать{}, // приглашать в дом
rus_verbs:понестись{}, // понестись в ворота
rus_verbs:заехать{}, // заехать в гаражный бокс
rus_verbs:опускаться{}, // опускаться в бездну
rus_verbs:переехать{}, // переехать в коттедж
rus_verbs:поместить{}, // поместить в карантин
rus_verbs:ползти{}, // ползти в нору
rus_verbs:добавлять{}, // добавлять в корзину
rus_verbs:уткнуться{}, // уткнуться в подушку
rus_verbs:продавать{}, // продавать в рабство
rus_verbs:спрятаться{}, // Белка спрячется в дупло.
rus_verbs:врисовывать{}, // врисовывать новый персонаж в анимацию
rus_verbs:воткнуть{}, // воткни вилку в розетку
rus_verbs:нести{}, // нести в больницу
rus_verbs:воткнуться{}, // вилка воткнулась в сочную котлетку
rus_verbs:впаивать{}, // впаивать деталь в плату
rus_verbs:впаиваться{}, // деталь впаивается в плату
rus_verbs:впархивать{}, // впархивать в помещение
rus_verbs:впаять{}, // впаять деталь в плату
rus_verbs:впендюривать{}, // впендюривать штукенцию в агрегат
rus_verbs:впендюрить{}, // впендюрить штукенцию в агрегат
rus_verbs:вперивать{}, // вперивать взгляд в экран
rus_verbs:впериваться{}, // впериваться в экран
rus_verbs:вперить{}, // вперить взгляд в экран
rus_verbs:впериться{}, // впериться в экран
rus_verbs:вперять{}, // вперять взгляд в экран
rus_verbs:вперяться{}, // вперяться в экран
rus_verbs:впечатать{}, // впечатать текст в первую главу
rus_verbs:впечататься{}, // впечататься в стену
rus_verbs:впечатывать{}, // впечатывать текст в первую главу
rus_verbs:впечатываться{}, // впечатываться в стену
rus_verbs:впиваться{}, // Хищник впивается в жертву мощными зубами
rus_verbs:впитаться{}, // Жидкость впиталась в ткань
rus_verbs:впитываться{}, // Жидкость впитывается в ткань
rus_verbs:впихивать{}, // Мама впихивает в сумку кусок колбасы
rus_verbs:впихиваться{}, // Кусок колбасы впихивается в сумку
rus_verbs:впихнуть{}, // Мама впихнула кастрюлю в холодильник
rus_verbs:впихнуться{}, // Кастрюля впихнулась в холодильник
rus_verbs:вплавиться{}, // Провод вплавился в плату
rus_verbs:вплеснуть{}, // вплеснуть краситель в бак
rus_verbs:вплести{}, // вплести ленту в волосы
rus_verbs:вплестись{}, // вплестись в волосы
rus_verbs:вплетать{}, // вплетать ленты в волосы
rus_verbs:вплывать{}, // корабль вплывает в порт
rus_verbs:вплыть{}, // яхта вплыла в бухту
rus_verbs:вползать{}, // дракон вползает в пещеру
rus_verbs:вползти{}, // дракон вполз в свою пещеру
rus_verbs:впорхнуть{}, // бабочка впорхнула в окно
rus_verbs:впрессовать{}, // впрессовать деталь в плиту
rus_verbs:впрессоваться{}, // впрессоваться в плиту
rus_verbs:впрессовывать{}, // впрессовывать деталь в плиту
rus_verbs:впрессовываться{}, // впрессовываться в плиту
rus_verbs:впрыгивать{}, // Пассажир впрыгивает в вагон
rus_verbs:впрыгнуть{}, // Пассажир впрыгнул в вагон
rus_verbs:впрыскивать{}, // Форсунка впрыскивает топливо в цилиндр
rus_verbs:впрыскиваться{}, // Топливо впрыскивается форсункой в цилиндр
rus_verbs:впрыснуть{}, // Форсунка впрыснула топливную смесь в камеру сгорания
rus_verbs:впрягать{}, // впрягать лошадь в телегу
rus_verbs:впрягаться{}, // впрягаться в работу
rus_verbs:впрячь{}, // впрячь лошадь в телегу
rus_verbs:впрячься{}, // впрячься в работу
rus_verbs:впускать{}, // впускать посетителей в музей
rus_verbs:впускаться{}, // впускаться в помещение
rus_verbs:впустить{}, // впустить посетителей в музей
rus_verbs:впутать{}, // впутать кого-то во что-то
rus_verbs:впутаться{}, // впутаться во что-то
rus_verbs:впутывать{}, // впутывать кого-то во что-то
rus_verbs:впутываться{}, // впутываться во что-то
rus_verbs:врабатываться{}, // врабатываться в режим
rus_verbs:вработаться{}, // вработаться в режим
rus_verbs:врастать{}, // врастать в кожу
rus_verbs:врасти{}, // врасти в кожу
инфинитив:врезать{ вид:несоверш }, // врезать замок в дверь
инфинитив:врезать{ вид:соверш },
глагол:врезать{ вид:несоверш },
глагол:врезать{ вид:соверш },
деепричастие:врезая{},
деепричастие:врезав{},
прилагательное:врезанный{},
инфинитив:врезаться{ вид:несоверш }, // врезаться в стену
инфинитив:врезаться{ вид:соверш },
глагол:врезаться{ вид:несоверш },
деепричастие:врезаясь{},
деепричастие:врезавшись{},
rus_verbs:врубить{}, // врубить в нагрузку
rus_verbs:врываться{}, // врываться в здание
rus_verbs:закачивать{}, // Насос закачивает топливо в бак
rus_verbs:ввезти{}, // Предприятие ввезло товар в страну
rus_verbs:вверстать{}, // Дизайнер вверстал блок в страницу
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:вверстываться{}, // Блок тяжело вверстывается в эту страницу
rus_verbs:ввивать{}, // Женщина ввивает полоску в косу
rus_verbs:вволакиваться{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вволочь{}, // Кот вволок в дом пойманную крысу
rus_verbs:вдергивать{}, // приспособление вдергивает нитку в игольное ушко
rus_verbs:вдернуть{}, // приспособление вдернуло нитку в игольное ушко
rus_verbs:вдувать{}, // Челоек вдувает воздух в легкие второго человека
rus_verbs:вдуваться{}, // Воздух вдувается в легкие человека
rus_verbs:вламываться{}, // Полиция вламывается в квартиру
rus_verbs:вовлекаться{}, // трудные подростки вовлекаются в занятие спортом
rus_verbs:вовлечь{}, // вовлечь трудных подростков в занятие спортом
rus_verbs:вовлечься{}, // вовлечься в занятие спортом
rus_verbs:спуститься{}, // спуститься в подвал
rus_verbs:спускаться{}, // спускаться в подвал
rus_verbs:отправляться{}, // отправляться в дальнее плавание
инфинитив:эмитировать{ вид:соверш }, // Поверхность эмитирует электроны в пространство
инфинитив:эмитировать{ вид:несоверш },
глагол:эмитировать{ вид:соверш },
глагол:эмитировать{ вид:несоверш },
деепричастие:эмитируя{},
деепричастие:эмитировав{},
прилагательное:эмитировавший{ вид:несоверш },
// прилагательное:эмитировавший{ вид:соверш },
прилагательное:эмитирующий{},
прилагательное:эмитируемый{},
прилагательное:эмитированный{},
инфинитив:этапировать{вид:несоверш}, // Преступника этапировали в колонию
инфинитив:этапировать{вид:соверш},
глагол:этапировать{вид:несоверш},
глагол:этапировать{вид:соверш},
деепричастие:этапируя{},
прилагательное:этапируемый{},
прилагательное:этапированный{},
rus_verbs:этапироваться{}, // Преступники этапируются в колонию
rus_verbs:баллотироваться{}, // они баллотировались в жюри
rus_verbs:бежать{}, // Олигарх с семьей любовницы бежал в другую страну
rus_verbs:бросать{}, // Они бросали в фонтан медные монетки
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:бросить{}, // Он бросил в фонтан медную монетку
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:превратить{}, // Найден белок, который превратит человека в супергероя
rus_verbs:буксировать{}, // Буксир буксирует танкер в порт
rus_verbs:буксироваться{}, // Сухогруз буксируется в порт
rus_verbs:вбегать{}, // Курьер вбегает в дверь
rus_verbs:вбежать{}, // Курьер вбежал в дверь
rus_verbs:вбетонировать{}, // Опора была вбетонирована в пол
rus_verbs:вбивать{}, // Мастер вбивает штырь в плиту
rus_verbs:вбиваться{}, // Штырь вбивается в плиту
rus_verbs:вбирать{}, // Вата вбирает в себя влагу
rus_verbs:вбить{}, // Ученик вбил в доску маленький гвоздь
rus_verbs:вбрасывать{}, // Арбитр вбрасывает мяч в игру
rus_verbs:вбрасываться{}, // Мяч вбрасывается в игру
rus_verbs:вбросить{}, // Судья вбросил мяч в игру
rus_verbs:вбуравиться{}, // Сверло вбуравилось в бетон
rus_verbs:вбуравливаться{}, // Сверло вбуравливается в бетон
rus_verbs:вбухиваться{}, // Много денег вбухиваются в этот проект
rus_verbs:вваливаться{}, // Человек вваливается в кабинет врача
rus_verbs:ввалить{}, // Грузчики ввалили мешок в квартиру
rus_verbs:ввалиться{}, // Человек ввалился в кабинет терапевта
rus_verbs:вваривать{}, // Робот вваривает арматурину в плиту
rus_verbs:ввариваться{}, // Арматура вваривается в плиту
rus_verbs:вварить{}, // Робот вварил арматурину в плиту
rus_verbs:влезть{}, // Предприятие ввезло товар в страну
rus_verbs:ввернуть{}, // Вверни новую лампочку в люстру
rus_verbs:ввернуться{}, // Лампочка легко ввернулась в патрон
rus_verbs:ввертывать{}, // Электрик ввертывает лампочку в патрон
rus_verbs:ввертываться{}, // Лампочка легко ввертывается в патрон
rus_verbs:вверять{}, // Пациент вверяет свою жизнь в руки врача
rus_verbs:вверяться{}, // Пациент вверяется в руки врача
rus_verbs:ввести{}, // Агенство ввело своего представителя в совет директоров
rus_verbs:ввиваться{}, // полоска ввивается в косу
rus_verbs:ввинтить{}, // Отвертка ввинтила шуруп в дерево
rus_verbs:ввинтиться{}, // Шуруп ввинтился в дерево
rus_verbs:ввинчивать{}, // Рука ввинчивает саморез в стену
rus_verbs:ввинчиваться{}, // Саморез ввинчивается в стену
rus_verbs:вводить{}, // Агенство вводит своего представителя в совет директоров
rus_verbs:вводиться{}, // Представитель агенства вводится в совет директоров
// rus_verbs:ввозить{}, // Фирма ввозит в страну станки и сырье
rus_verbs:ввозиться{}, // Станки и сырье ввозятся в страну
rus_verbs:вволакивать{}, // Пойманная мышь вволакивается котиком в дом
rus_verbs:вворачивать{}, // Электрик вворачивает новую лампочку в патрон
rus_verbs:вворачиваться{}, // Новая лампочка легко вворачивается в патрон
rus_verbs:ввязаться{}, // Разведрота ввязалась в бой
rus_verbs:ввязываться{}, // Передовые части ввязываются в бой
rus_verbs:вглядеться{}, // Охранник вгляделся в темный коридор
rus_verbs:вглядываться{}, // Охранник внимательно вглядывается в монитор
rus_verbs:вгонять{}, // Эта музыка вгоняет меня в депрессию
rus_verbs:вгрызаться{}, // Зонд вгрызается в поверхность астероида
rus_verbs:вгрызться{}, // Зонд вгрызся в поверхность астероида
rus_verbs:вдаваться{}, // Вы не должны вдаваться в юридические детали
rus_verbs:вдвигать{}, // Робот вдвигает контейнер в ячейку
rus_verbs:вдвигаться{}, // Контейнер вдвигается в ячейку
rus_verbs:вдвинуть{}, // манипулятор вдвинул деталь в печь
rus_verbs:вдвинуться{}, // деталь вдвинулась в печь
rus_verbs:вдевать{}, // портниха быстро вдевает нитку в иголку
rus_verbs:вдеваться{}, // нитка быстро вдевается в игольное ушко
rus_verbs:вдеть{}, // портниха быстро вдела нитку в игольное ушко
rus_verbs:вдеться{}, // нитка быстро вделась в игольное ушко
rus_verbs:вделать{}, // мастер вделал розетку в стену
rus_verbs:вделывать{}, // мастер вделывает выключатель в стену
rus_verbs:вделываться{}, // кронштейн вделывается в стену
rus_verbs:вдергиваться{}, // нитка легко вдергивается в игольное ушко
rus_verbs:вдернуться{}, // нитка легко вдернулась в игольное ушко
rus_verbs:вдолбить{}, // Американцы обещали вдолбить страну в каменный век
rus_verbs:вдумываться{}, // Мальчик обычно не вдумывался в сюжет фильмов
rus_verbs:вдыхать{}, // мы вдыхаем в себя весь этот смог
rus_verbs:вдыхаться{}, // Весь этот смог вдыхается в легкие
rus_verbs:вернуть{}, // Книгу надо вернуть в библиотеку
rus_verbs:вернуться{}, // Дети вернулись в библиотеку
rus_verbs:вжаться{}, // Водитель вжался в кресло
rus_verbs:вживаться{}, // Актер вживается в новую роль
rus_verbs:вживить{}, // Врачи вживили стимулятор в тело пациента
rus_verbs:вживиться{}, // Стимулятор вживился в тело пациента
rus_verbs:вживлять{}, // Врачи вживляют стимулятор в тело пациента
rus_verbs:вживляться{}, // Стимулятор вживляется в тело
rus_verbs:вжиматься{}, // Видитель инстинктивно вжимается в кресло
rus_verbs:вжиться{}, // Актер вжился в свою новую роль
rus_verbs:взвиваться{}, // Воздушный шарик взвивается в небо
rus_verbs:взвинтить{}, // Кризис взвинтил цены в небо
rus_verbs:взвинтиться{}, // Цены взвинтились в небо
rus_verbs:взвинчивать{}, // Кризис взвинчивает цены в небо
rus_verbs:взвинчиваться{}, // Цены взвинчиваются в небо
rus_verbs:взвиться{}, // Шарики взвились в небо
rus_verbs:взлетать{}, // Экспериментальный аппарат взлетает в воздух
rus_verbs:взлететь{}, // Экспериментальный аппарат взлетел в небо
rus_verbs:взмывать{}, // шарики взмывают в небо
rus_verbs:взмыть{}, // Шарики взмыли в небо
rus_verbs:вильнуть{}, // Машина вильнула в левую сторону
rus_verbs:вкалывать{}, // Медсестра вкалывает иглу в вену
rus_verbs:вкалываться{}, // Игла вкалываться прямо в вену
rus_verbs:вкапывать{}, // рабочий вкапывает сваю в землю
rus_verbs:вкапываться{}, // Свая вкапывается в землю
rus_verbs:вкатить{}, // рабочие вкатили бочку в гараж
rus_verbs:вкатиться{}, // машина вкатилась в гараж
rus_verbs:вкатывать{}, // рабочик вкатывают бочку в гараж
rus_verbs:вкатываться{}, // машина вкатывается в гараж
rus_verbs:вкачать{}, // Механики вкачали в бак много топлива
rus_verbs:вкачивать{}, // Насос вкачивает топливо в бак
rus_verbs:вкачиваться{}, // Топливо вкачивается в бак
rus_verbs:вкидать{}, // Манипулятор вкидал груз в контейнер
rus_verbs:вкидывать{}, // Манипулятор вкидывает груз в контейнер
rus_verbs:вкидываться{}, // Груз вкидывается в контейнер
rus_verbs:вкладывать{}, // Инвестор вкладывает деньги в акции
rus_verbs:вкладываться{}, // Инвестор вкладывается в акции
rus_verbs:вклеивать{}, // Мальчик вклеивает картинку в тетрадь
rus_verbs:вклеиваться{}, // Картинка вклеивается в тетрадь
rus_verbs:вклеить{}, // Мальчик вклеил картинку в тетрадь
rus_verbs:вклеиться{}, // Картинка вклеилась в тетрадь
rus_verbs:вклепать{}, // Молоток вклепал заклепку в лист
rus_verbs:вклепывать{}, // Молоток вклепывает заклепку в лист
rus_verbs:вклиниваться{}, // Машина вклинивается в поток
rus_verbs:вклиниться{}, // машина вклинилась в поток
rus_verbs:включать{}, // Команда включает компьютер в сеть
rus_verbs:включаться{}, // Машина включается в глобальную сеть
rus_verbs:включить{}, // Команда включила компьютер в сеть
rus_verbs:включиться{}, // Компьютер включился в сеть
rus_verbs:вколачивать{}, // Столяр вколачивает гвоздь в доску
rus_verbs:вколачиваться{}, // Гвоздь вколачивается в доску
rus_verbs:вколотить{}, // Столяр вколотил гвоздь в доску
rus_verbs:вколоть{}, // Медсестра вколола в мышцу лекарство
rus_verbs:вкопать{}, // Рабочие вкопали сваю в землю
rus_verbs:вкрадываться{}, // Ошибка вкрадывается в расчеты
rus_verbs:вкраивать{}, // Портниха вкраивает вставку в юбку
rus_verbs:вкраиваться{}, // Вставка вкраивается в юбку
rus_verbs:вкрасться{}, // Ошибка вкралась в расчеты
rus_verbs:вкрутить{}, // Электрик вкрутил лампочку в патрон
rus_verbs:вкрутиться{}, // лампочка легко вкрутилась в патрон
rus_verbs:вкручивать{}, // Электрик вкручивает лампочку в патрон
rus_verbs:вкручиваться{}, // Лампочка легко вкручивается в патрон
rus_verbs:влазить{}, // Разъем влазит в отверствие
rus_verbs:вламывать{}, // Полиция вламывается в квартиру
rus_verbs:влетать{}, // Самолет влетает в грозовой фронт
rus_verbs:влететь{}, // Самолет влетел в грозовой фронт
rus_verbs:вливать{}, // Механик вливает масло в картер
rus_verbs:вливаться{}, // Масло вливается в картер
rus_verbs:влипать{}, // Эти неудачники постоянно влипают в разные происшествия
rus_verbs:влипнуть{}, // Эти неудачники опять влипли в неприятности
rus_verbs:влить{}, // Механик влил свежее масло в картер
rus_verbs:влиться{}, // Свежее масло влилось в бак
rus_verbs:вложить{}, // Инвесторы вложили в эти акции большие средства
rus_verbs:вложиться{}, // Инвесторы вложились в эти акции
rus_verbs:влюбиться{}, // Коля влюбился в Олю
rus_verbs:влюблять{}, // Оля постоянно влюбляла в себя мальчиков
rus_verbs:влюбляться{}, // Оля влюбляется в спортсменов
rus_verbs:вляпаться{}, // Коля вляпался в неприятность
rus_verbs:вляпываться{}, // Коля постоянно вляпывается в неприятности
rus_verbs:вменить{}, // вменить в вину
rus_verbs:вменять{}, // вменять в обязанность
rus_verbs:вмерзать{}, // Колеса вмерзают в лед
rus_verbs:вмерзнуть{}, // Колеса вмерзли в лед
rus_verbs:вмести{}, // вмести в дом
rus_verbs:вместить{}, // вместить в ёмкость
rus_verbs:вместиться{}, // Прибор не вместился в зонд
rus_verbs:вмешаться{}, // Начальник вмешался в конфликт
rus_verbs:вмешивать{}, // Не вмешивай меня в это дело
rus_verbs:вмешиваться{}, // Начальник вмешивается в переговоры
rus_verbs:вмещаться{}, // Приборы не вмещаются в корпус
rus_verbs:вминать{}, // вминать в корпус
rus_verbs:вминаться{}, // кронштейн вминается в корпус
rus_verbs:вмонтировать{}, // Конструкторы вмонтировали в корпус зонда новые приборы
rus_verbs:вмонтироваться{}, // Новые приборы легко вмонтировались в корпус зонда
rus_verbs:вмораживать{}, // Установка вмораживает сваи в грунт
rus_verbs:вмораживаться{}, // Сваи вмораживаются в грунт
rus_verbs:вморозить{}, // Установка вморозила сваи в грунт
rus_verbs:вмуровать{}, // Сейф был вмурован в стену
rus_verbs:вмуровывать{}, // вмуровывать сейф в стену
rus_verbs:вмуровываться{}, // сейф вмуровывается в бетонную стену
rus_verbs:внедрить{}, // внедрить инновацию в производство
rus_verbs:внедриться{}, // Шпион внедрился в руководство
rus_verbs:внедрять{}, // внедрять инновации в производство
rus_verbs:внедряться{}, // Шпионы внедряются в руководство
rus_verbs:внести{}, // внести коробку в дом
rus_verbs:внестись{}, // внестись в список приглашенных гостей
rus_verbs:вникать{}, // Разработчик вникает в детали задачи
rus_verbs:вникнуть{}, // Дизайнер вник в детали задачи
rus_verbs:вносить{}, // вносить новое действующее лицо в список главных героев
rus_verbs:вноситься{}, // вноситься в список главных персонажей
rus_verbs:внюхаться{}, // Пёс внюхался в ароматы леса
rus_verbs:внюхиваться{}, // Пёс внюхивается в ароматы леса
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:вовлекать{}, // вовлекать трудных подростков в занятие спортом
rus_verbs:вогнать{}, // вогнал человека в тоску
rus_verbs:водворить{}, // водворить преступника в тюрьму
rus_verbs:возвернуть{}, // возвернуть в родную стихию
rus_verbs:возвернуться{}, // возвернуться в родную стихию
rus_verbs:возвести{}, // возвести число в четную степень
rus_verbs:возводить{}, // возводить число в четную степень
rus_verbs:возводиться{}, // число возводится в четную степень
rus_verbs:возвратить{}, // возвратить коров в стойло
rus_verbs:возвратиться{}, // возвратиться в родной дом
rus_verbs:возвращать{}, // возвращать коров в стойло
rus_verbs:возвращаться{}, // возвращаться в родной дом
rus_verbs:войти{}, // войти в галерею славы
rus_verbs:вонзать{}, // Коля вонзает вилку в котлету
rus_verbs:вонзаться{}, // Вилка вонзается в котлету
rus_verbs:вонзить{}, // Коля вонзил вилку в котлету
rus_verbs:вонзиться{}, // Вилка вонзилась в сочную котлету
rus_verbs:воплотить{}, // Коля воплотил свои мечты в реальность
rus_verbs:воплотиться{}, // Мечты воплотились в реальность
rus_verbs:воплощать{}, // Коля воплощает мечты в реальность
rus_verbs:воплощаться{}, // Мечты иногда воплощаются в реальность
rus_verbs:ворваться{}, // Перемены неожиданно ворвались в размеренную жизнь
rus_verbs:воспарить{}, // Душа воспарила в небо
rus_verbs:воспарять{}, // Душа воспаряет в небо
rus_verbs:врыть{}, // врыть опору в землю
rus_verbs:врыться{}, // врыться в землю
rus_verbs:всадить{}, // всадить пулю в сердце
rus_verbs:всаживать{}, // всаживать нож в бок
rus_verbs:всасывать{}, // всасывать воду в себя
rus_verbs:всасываться{}, // всасываться в ёмкость
rus_verbs:вселить{}, // вселить надежду в кого-либо
rus_verbs:вселиться{}, // вселиться в пустующее здание
rus_verbs:вселять{}, // вселять надежду в кого-то
rus_verbs:вселяться{}, // вселяться в пустующее здание
rus_verbs:вскидывать{}, // вскидывать руку в небо
rus_verbs:вскинуть{}, // вскинуть руку в небо
rus_verbs:вслушаться{}, // вслушаться в звуки
rus_verbs:вслушиваться{}, // вслушиваться в шорох
rus_verbs:всматриваться{}, // всматриваться в темноту
rus_verbs:всмотреться{}, // всмотреться в темень
rus_verbs:всовывать{}, // всовывать палец в отверстие
rus_verbs:всовываться{}, // всовываться в форточку
rus_verbs:всосать{}, // всосать жидкость в себя
rus_verbs:всосаться{}, // всосаться в кожу
rus_verbs:вставить{}, // вставить ключ в замок
rus_verbs:вставлять{}, // вставлять ключ в замок
rus_verbs:встраивать{}, // встраивать черный ход в систему защиты
rus_verbs:встраиваться{}, // встраиваться в систему безопасности
rus_verbs:встревать{}, // встревать в разговор
rus_verbs:встроить{}, // встроить секретный модуль в систему безопасности
rus_verbs:встроиться{}, // встроиться в систему безопасности
rus_verbs:встрять{}, // встрять в разговор
rus_verbs:вступать{}, // вступать в действующую армию
rus_verbs:вступить{}, // вступить в действующую армию
rus_verbs:всунуть{}, // всунуть палец в отверстие
rus_verbs:всунуться{}, // всунуться в форточку
инфинитив:всыпать{вид:соверш}, // всыпать порошок в контейнер
инфинитив:всыпать{вид:несоверш},
глагол:всыпать{вид:соверш},
глагол:всыпать{вид:несоверш},
деепричастие:всыпав{},
деепричастие:всыпая{},
прилагательное:всыпавший{ вид:соверш },
// прилагательное:всыпавший{ вид:несоверш },
прилагательное:всыпанный{},
// прилагательное:всыпающий{},
инфинитив:всыпаться{ вид:несоверш}, // всыпаться в контейнер
// инфинитив:всыпаться{ вид:соверш},
// глагол:всыпаться{ вид:соверш},
глагол:всыпаться{ вид:несоверш},
// деепричастие:всыпавшись{},
деепричастие:всыпаясь{},
// прилагательное:всыпавшийся{ вид:соверш },
// прилагательное:всыпавшийся{ вид:несоверш },
// прилагательное:всыпающийся{},
rus_verbs:вталкивать{}, // вталкивать деталь в ячейку
rus_verbs:вталкиваться{}, // вталкиваться в ячейку
rus_verbs:втаптывать{}, // втаптывать в грязь
rus_verbs:втаптываться{}, // втаптываться в грязь
rus_verbs:втаскивать{}, // втаскивать мешок в комнату
rus_verbs:втаскиваться{}, // втаскиваться в комнату
rus_verbs:втащить{}, // втащить мешок в комнату
rus_verbs:втащиться{}, // втащиться в комнату
rus_verbs:втекать{}, // втекать в бутылку
rus_verbs:втемяшивать{}, // втемяшивать в голову
rus_verbs:втемяшиваться{}, // втемяшиваться в голову
rus_verbs:втемяшить{}, // втемяшить в голову
rus_verbs:втемяшиться{}, // втемяшиться в голову
rus_verbs:втереть{}, // втереть крем в кожу
rus_verbs:втереться{}, // втереться в кожу
rus_verbs:втесаться{}, // втесаться в группу
rus_verbs:втесывать{}, // втесывать в группу
rus_verbs:втесываться{}, // втесываться в группу
rus_verbs:втечь{}, // втечь в бак
rus_verbs:втирать{}, // втирать крем в кожу
rus_verbs:втираться{}, // втираться в кожу
rus_verbs:втискивать{}, // втискивать сумку в вагон
rus_verbs:втискиваться{}, // втискиваться в переполненный вагон
rus_verbs:втиснуть{}, // втиснуть сумку в вагон
rus_verbs:втиснуться{}, // втиснуться в переполненный вагон метро
rus_verbs:втолкать{}, // втолкать коляску в лифт
rus_verbs:втолкаться{}, // втолкаться в вагон метро
rus_verbs:втолкнуть{}, // втолкнуть коляску в лифт
rus_verbs:втолкнуться{}, // втолкнуться в вагон метро
rus_verbs:втолочь{}, // втолочь в смесь
rus_verbs:втоптать{}, // втоптать цветы в землю
rus_verbs:вторгаться{}, // вторгаться в чужую зону
rus_verbs:вторгнуться{}, // вторгнуться в частную жизнь
rus_verbs:втравить{}, // втравить кого-то в неприятности
rus_verbs:втравливать{}, // втравливать кого-то в неприятности
rus_verbs:втрамбовать{}, // втрамбовать камни в землю
rus_verbs:втрамбовывать{}, // втрамбовывать камни в землю
rus_verbs:втрамбовываться{}, // втрамбовываться в землю
rus_verbs:втрескаться{}, // втрескаться в кого-то
rus_verbs:втрескиваться{}, // втрескиваться в кого-либо
rus_verbs:втыкать{}, // втыкать вилку в котлетку
rus_verbs:втыкаться{}, // втыкаться в розетку
rus_verbs:втюриваться{}, // втюриваться в кого-либо
rus_verbs:втюриться{}, // втюриться в кого-либо
rus_verbs:втягивать{}, // втягивать что-то в себя
rus_verbs:втягиваться{}, // втягиваться в себя
rus_verbs:втянуться{}, // втянуться в себя
rus_verbs:вцементировать{}, // вцементировать сваю в фундамент
rus_verbs:вчеканить{}, // вчеканить надпись в лист
rus_verbs:вчитаться{}, // вчитаться внимательнее в текст
rus_verbs:вчитываться{}, // вчитываться внимательнее в текст
rus_verbs:вчувствоваться{}, // вчувствоваться в роль
rus_verbs:вшагивать{}, // вшагивать в новую жизнь
rus_verbs:вшагнуть{}, // вшагнуть в новую жизнь
rus_verbs:вшивать{}, // вшивать заплату в рубашку
rus_verbs:вшиваться{}, // вшиваться в ткань
rus_verbs:вшить{}, // вшить заплату в ткань
rus_verbs:въедаться{}, // въедаться в мякоть
rus_verbs:въезжать{}, // въезжать в гараж
rus_verbs:въехать{}, // въехать в гараж
rus_verbs:выиграть{}, // Коля выиграл в шахматы
rus_verbs:выигрывать{}, // Коля часто выигрывает у меня в шахматы
rus_verbs:выкладывать{}, // выкладывать в общий доступ
rus_verbs:выкладываться{}, // выкладываться в общий доступ
rus_verbs:выкрасить{}, // выкрасить машину в розовый цвет
rus_verbs:выкраситься{}, // выкраситься в дерзкий розовый цвет
rus_verbs:выкрашивать{}, // выкрашивать волосы в красный цвет
rus_verbs:выкрашиваться{}, // выкрашиваться в красный цвет
rus_verbs:вылезать{}, // вылезать в открытое пространство
rus_verbs:вылезти{}, // вылезти в открытое пространство
rus_verbs:выливать{}, // выливать в бутылку
rus_verbs:выливаться{}, // выливаться в ёмкость
rus_verbs:вылить{}, // вылить отходы в канализацию
rus_verbs:вылиться{}, // Топливо вылилось в воду
rus_verbs:выложить{}, // выложить в общий доступ
rus_verbs:выпадать{}, // выпадать в осадок
rus_verbs:выпрыгивать{}, // выпрыгивать в окно
rus_verbs:выпрыгнуть{}, // выпрыгнуть в окно
rus_verbs:выродиться{}, // выродиться в жалкое подобие
rus_verbs:вырождаться{}, // вырождаться в жалкое подобие славных предков
rus_verbs:высеваться{}, // высеваться в землю
rus_verbs:высеять{}, // высеять в землю
rus_verbs:выслать{}, // выслать в страну постоянного пребывания
rus_verbs:высморкаться{}, // высморкаться в платок
rus_verbs:высморкнуться{}, // высморкнуться в платок
rus_verbs:выстреливать{}, // выстреливать в цель
rus_verbs:выстреливаться{}, // выстреливаться в цель
rus_verbs:выстрелить{}, // выстрелить в цель
rus_verbs:вытекать{}, // вытекать в озеро
rus_verbs:вытечь{}, // вытечь в воду
rus_verbs:смотреть{}, // смотреть в будущее
rus_verbs:подняться{}, // подняться в лабораторию
rus_verbs:послать{}, // послать в магазин
rus_verbs:слать{}, // слать в неизвестность
rus_verbs:добавить{}, // добавить в суп
rus_verbs:пройти{}, // пройти в лабораторию
rus_verbs:положить{}, // положить в ящик
rus_verbs:прислать{}, // прислать в полицию
rus_verbs:упасть{}, // упасть в пропасть
инфинитив:писать{ aux stress="пис^ать" }, // писать в газету
инфинитив:писать{ aux stress="п^исать" }, // писать в штанишки
глагол:писать{ aux stress="п^исать" },
глагол:писать{ aux stress="пис^ать" },
деепричастие:писая{},
прилагательное:писавший{ aux stress="п^исавший" }, // писавший в штанишки
прилагательное:писавший{ aux stress="пис^авший" }, // писавший в газету
rus_verbs:собираться{}, // собираться в поход
rus_verbs:звать{}, // звать в ресторан
rus_verbs:направиться{}, // направиться в ресторан
rus_verbs:отправиться{}, // отправиться в ресторан
rus_verbs:поставить{}, // поставить в угол
rus_verbs:целить{}, // целить в мишень
rus_verbs:попасть{}, // попасть в переплет
rus_verbs:ударить{}, // ударить в больное место
rus_verbs:закричать{}, // закричать в микрофон
rus_verbs:опустить{}, // опустить в воду
rus_verbs:принести{}, // принести в дом бездомного щенка
rus_verbs:отдать{}, // отдать в хорошие руки
rus_verbs:ходить{}, // ходить в школу
rus_verbs:уставиться{}, // уставиться в экран
rus_verbs:приходить{}, // приходить в бешенство
rus_verbs:махнуть{}, // махнуть в Италию
rus_verbs:сунуть{}, // сунуть в замочную скважину
rus_verbs:явиться{}, // явиться в расположение части
rus_verbs:уехать{}, // уехать в город
rus_verbs:целовать{}, // целовать в лобик
rus_verbs:повести{}, // повести в бой
rus_verbs:опуститься{}, // опуститься в кресло
rus_verbs:передать{}, // передать в архив
rus_verbs:побежать{}, // побежать в школу
rus_verbs:стечь{}, // стечь в воду
rus_verbs:уходить{}, // уходить добровольцем в армию
rus_verbs:привести{}, // привести в дом
rus_verbs:шагнуть{}, // шагнуть в неизвестность
rus_verbs:собраться{}, // собраться в поход
rus_verbs:заглянуть{}, // заглянуть в основу
rus_verbs:поспешить{}, // поспешить в церковь
rus_verbs:поцеловать{}, // поцеловать в лоб
rus_verbs:перейти{}, // перейти в высшую лигу
rus_verbs:поверить{}, // поверить в искренность
rus_verbs:глянуть{}, // глянуть в оглавление
rus_verbs:зайти{}, // зайти в кафетерий
rus_verbs:подобрать{}, // подобрать в лесу
rus_verbs:проходить{}, // проходить в помещение
rus_verbs:глядеть{}, // глядеть в глаза
rus_verbs:пригласить{}, // пригласить в театр
rus_verbs:позвать{}, // позвать в класс
rus_verbs:усесться{}, // усесться в кресло
rus_verbs:поступить{}, // поступить в институт
rus_verbs:лечь{}, // лечь в постель
rus_verbs:поклониться{}, // поклониться в пояс
rus_verbs:потянуться{}, // потянуться в лес
rus_verbs:колоть{}, // колоть в ягодицу
rus_verbs:присесть{}, // присесть в кресло
rus_verbs:оглядеться{}, // оглядеться в зеркало
rus_verbs:поглядеть{}, // поглядеть в зеркало
rus_verbs:превратиться{}, // превратиться в лягушку
rus_verbs:принимать{}, // принимать во внимание
rus_verbs:звонить{}, // звонить в колокола
rus_verbs:привезти{}, // привезти в гостиницу
rus_verbs:рухнуть{}, // рухнуть в пропасть
rus_verbs:пускать{}, // пускать в дело
rus_verbs:отвести{}, // отвести в больницу
rus_verbs:сойти{}, // сойти в ад
rus_verbs:набрать{}, // набрать в команду
rus_verbs:собрать{}, // собрать в кулак
rus_verbs:двигаться{}, // двигаться в каюту
rus_verbs:падать{}, // падать в область нуля
rus_verbs:полезть{}, // полезть в драку
rus_verbs:направить{}, // направить в стационар
rus_verbs:приводить{}, // приводить в чувство
rus_verbs:толкнуть{}, // толкнуть в бок
rus_verbs:кинуться{}, // кинуться в драку
rus_verbs:ткнуть{}, // ткнуть в глаз
rus_verbs:заключить{}, // заключить в объятия
rus_verbs:подниматься{}, // подниматься в небо
rus_verbs:расти{}, // расти в глубину
rus_verbs:налить{}, // налить в кружку
rus_verbs:швырнуть{}, // швырнуть в бездну
rus_verbs:прыгнуть{}, // прыгнуть в дверь
rus_verbs:промолчать{}, // промолчать в тряпочку
rus_verbs:садиться{}, // садиться в кресло
rus_verbs:лить{}, // лить в кувшин
rus_verbs:дослать{}, // дослать деталь в держатель
rus_verbs:переслать{}, // переслать в обработчик
rus_verbs:удалиться{}, // удалиться в совещательную комнату
rus_verbs:разглядывать{}, // разглядывать в бинокль
rus_verbs:повесить{}, // повесить в шкаф
инфинитив:походить{ вид:соверш }, // походить в институт
глагол:походить{ вид:соверш },
деепричастие:походив{},
// прилагательное:походивший{вид:соверш},
rus_verbs:помчаться{}, // помчаться в класс
rus_verbs:свалиться{}, // свалиться в яму
rus_verbs:сбежать{}, // сбежать в Англию
rus_verbs:стрелять{}, // стрелять в цель
rus_verbs:обращать{}, // обращать в свою веру
rus_verbs:завести{}, // завести в дом
rus_verbs:приобрести{}, // приобрести в рассрочку
rus_verbs:сбросить{}, // сбросить в яму
rus_verbs:устроиться{}, // устроиться в крупную корпорацию
rus_verbs:погрузиться{}, // погрузиться в пучину
rus_verbs:течь{}, // течь в канаву
rus_verbs:произвести{}, // произвести в звание майора
rus_verbs:метать{}, // метать в цель
rus_verbs:пустить{}, // пустить в дело
rus_verbs:полететь{}, // полететь в Европу
rus_verbs:пропустить{}, // пропустить в здание
rus_verbs:рвануть{}, // рвануть в отпуск
rus_verbs:заходить{}, // заходить в каморку
rus_verbs:нырнуть{}, // нырнуть в прорубь
rus_verbs:рвануться{}, // рвануться в атаку
rus_verbs:приподняться{}, // приподняться в воздух
rus_verbs:превращаться{}, // превращаться в крупную величину
rus_verbs:прокричать{}, // прокричать в ухо
rus_verbs:записать{}, // записать в блокнот
rus_verbs:забраться{}, // забраться в шкаф
rus_verbs:приезжать{}, // приезжать в деревню
rus_verbs:продать{}, // продать в рабство
rus_verbs:проникнуть{}, // проникнуть в центр
rus_verbs:устремиться{}, // устремиться в открытое море
rus_verbs:посадить{}, // посадить в кресло
rus_verbs:упереться{}, // упереться в пол
rus_verbs:ринуться{}, // ринуться в буфет
rus_verbs:отдавать{}, // отдавать в кадетское училище
rus_verbs:отложить{}, // отложить в долгий ящик
rus_verbs:убежать{}, // убежать в приют
rus_verbs:оценить{}, // оценить в миллион долларов
rus_verbs:поднимать{}, // поднимать в стратосферу
rus_verbs:отослать{}, // отослать в квалификационную комиссию
rus_verbs:отодвинуть{}, // отодвинуть в дальний угол
rus_verbs:торопиться{}, // торопиться в школу
rus_verbs:попадаться{}, // попадаться в руки
rus_verbs:поразить{}, // поразить в самое сердце
rus_verbs:доставить{}, // доставить в квартиру
rus_verbs:заслать{}, // заслать в тыл
rus_verbs:сослать{}, // сослать в изгнание
rus_verbs:запустить{}, // запустить в космос
rus_verbs:удариться{}, // удариться в запой
rus_verbs:ударяться{}, // ударяться в крайность
rus_verbs:шептать{}, // шептать в лицо
rus_verbs:уронить{}, // уронить в унитаз
rus_verbs:прорычать{}, // прорычать в микрофон
rus_verbs:засунуть{}, // засунуть в глотку
rus_verbs:плыть{}, // плыть в открытое море
rus_verbs:перенести{}, // перенести в духовку
rus_verbs:светить{}, // светить в лицо
rus_verbs:мчаться{}, // мчаться в ремонт
rus_verbs:стукнуть{}, // стукнуть в лоб
rus_verbs:обрушиться{}, // обрушиться в котлован
rus_verbs:поглядывать{}, // поглядывать в экран
rus_verbs:уложить{}, // уложить в кроватку
инфинитив:попадать{ вид:несоверш }, // попадать в черный список
глагол:попадать{ вид:несоверш },
прилагательное:попадающий{ вид:несоверш },
прилагательное:попадавший{ вид:несоверш },
деепричастие:попадая{},
rus_verbs:провалиться{}, // провалиться в яму
rus_verbs:жаловаться{}, // жаловаться в комиссию
rus_verbs:опоздать{}, // опоздать в школу
rus_verbs:посылать{}, // посылать в парикмахерскую
rus_verbs:погнать{}, // погнать в хлев
rus_verbs:поступать{}, // поступать в институт
rus_verbs:усадить{}, // усадить в кресло
rus_verbs:проиграть{}, // проиграть в рулетку
rus_verbs:прилететь{}, // прилететь в страну
rus_verbs:повалиться{}, // повалиться в траву
rus_verbs:огрызнуться{}, // Собака огрызнулась в ответ
rus_verbs:лезть{}, // лезть в чужие дела
rus_verbs:потащить{}, // потащить в суд
rus_verbs:направляться{}, // направляться в порт
rus_verbs:поползти{}, // поползти в другую сторону
rus_verbs:пуститься{}, // пуститься в пляс
rus_verbs:забиться{}, // забиться в нору
rus_verbs:залезть{}, // залезть в конуру
rus_verbs:сдать{}, // сдать в утиль
rus_verbs:тронуться{}, // тронуться в путь
rus_verbs:сыграть{}, // сыграть в шахматы
rus_verbs:перевернуть{}, // перевернуть в более удобную позу
rus_verbs:сжимать{}, // сжимать пальцы в кулак
rus_verbs:подтолкнуть{}, // подтолкнуть в бок
rus_verbs:отнести{}, // отнести животное в лечебницу
rus_verbs:одеться{}, // одеться в зимнюю одежду
rus_verbs:плюнуть{}, // плюнуть в колодец
rus_verbs:передавать{}, // передавать в прокуратуру
rus_verbs:отскочить{}, // отскочить в лоб
rus_verbs:призвать{}, // призвать в армию
rus_verbs:увезти{}, // увезти в деревню
rus_verbs:улечься{}, // улечься в кроватку
rus_verbs:отшатнуться{}, // отшатнуться в сторону
rus_verbs:ложиться{}, // ложиться в постель
rus_verbs:пролететь{}, // пролететь в конец
rus_verbs:класть{}, // класть в сейф
rus_verbs:доставлять{}, // доставлять в кабинет
rus_verbs:приобретать{}, // приобретать в кредит
rus_verbs:сводить{}, // сводить в театр
rus_verbs:унести{}, // унести в могилу
rus_verbs:покатиться{}, // покатиться в яму
rus_verbs:сходить{}, // сходить в магазинчик
rus_verbs:спустить{}, // спустить в канализацию
rus_verbs:проникать{}, // проникать в сердцевину
rus_verbs:метнуть{}, // метнуть в болвана гневный взгляд
rus_verbs:пожаловаться{}, // пожаловаться в администрацию
rus_verbs:стучать{}, // стучать в металлическую дверь
rus_verbs:тащить{}, // тащить в ремонт
rus_verbs:заглядывать{}, // заглядывать в ответы
rus_verbs:плюхнуться{}, // плюхнуться в стол ароматного сена
rus_verbs:увести{}, // увести в следующий кабинет
rus_verbs:успевать{}, // успевать в школу
rus_verbs:пробраться{}, // пробраться в собачью конуру
rus_verbs:подавать{}, // подавать в суд
rus_verbs:прибежать{}, // прибежать в конюшню
rus_verbs:рассмотреть{}, // рассмотреть в микроскоп
rus_verbs:пнуть{}, // пнуть в живот
rus_verbs:завернуть{}, // завернуть в декоративную пленку
rus_verbs:уезжать{}, // уезжать в деревню
rus_verbs:привлекать{}, // привлекать в свои ряды
rus_verbs:перебраться{}, // перебраться в прибрежный город
rus_verbs:долить{}, // долить в коктейль
rus_verbs:палить{}, // палить в нападающих
rus_verbs:отобрать{}, // отобрать в коллекцию
rus_verbs:улететь{}, // улететь в неизвестность
rus_verbs:выглянуть{}, // выглянуть в окно
rus_verbs:выглядывать{}, // выглядывать в окно
rus_verbs:пробираться{}, // грабитель, пробирающийся в дом
инфинитив:написать{ aux stress="напис^ать"}, // читатель, написавший в блог
глагол:написать{ aux stress="напис^ать"},
прилагательное:написавший{ aux stress="напис^авший"},
rus_verbs:свернуть{}, // свернуть в колечко
инфинитив:сползать{ вид:несоверш }, // сползать в овраг
глагол:сползать{ вид:несоверш },
прилагательное:сползающий{ вид:несоверш },
прилагательное:сползавший{ вид:несоверш },
rus_verbs:барабанить{}, // барабанить в дверь
rus_verbs:дописывать{}, // дописывать в конец
rus_verbs:меняться{}, // меняться в лучшую сторону
rus_verbs:измениться{}, // измениться в лучшую сторону
rus_verbs:изменяться{}, // изменяться в лучшую сторону
rus_verbs:вписаться{}, // вписаться в поворот
rus_verbs:вписываться{}, // вписываться в повороты
rus_verbs:переработать{}, // переработать в удобрение
rus_verbs:перерабатывать{}, // перерабатывать в удобрение
rus_verbs:уползать{}, // уползать в тень
rus_verbs:заползать{}, // заползать в нору
rus_verbs:перепрятать{}, // перепрятать в укромное место
rus_verbs:заталкивать{}, // заталкивать в вагон
rus_verbs:преобразовывать{}, // преобразовывать в список
инфинитив:конвертировать{ вид:несоверш }, // конвертировать в список
глагол:конвертировать{ вид:несоверш },
инфинитив:конвертировать{ вид:соверш },
глагол:конвертировать{ вид:соверш },
деепричастие:конвертировав{},
деепричастие:конвертируя{},
rus_verbs:изорвать{}, // Он изорвал газету в клочки.
rus_verbs:выходить{}, // Окна выходят в сад.
rus_verbs:говорить{}, // Он говорил в защиту своего отца.
rus_verbs:вырастать{}, // Он вырастает в большого художника.
rus_verbs:вывести{}, // Он вывел детей в сад.
// инфинитив:всыпать{ вид:соверш }, инфинитив:всыпать{ вид:несоверш },
// глагол:всыпать{ вид:соверш }, глагол:всыпать{ вид:несоверш }, // Он всыпал в воду две ложки соли.
// прилагательное:раненый{}, // Он был ранен в левую руку.
// прилагательное:одетый{}, // Он был одет в толстое осеннее пальто.
rus_verbs:бухнуться{}, // Он бухнулся в воду.
rus_verbs:склонять{}, // склонять защиту в свою пользу
rus_verbs:впиться{}, // Пиявка впилась в тело.
rus_verbs:сходиться{}, // Интеллигенты начала века часто сходились в разные союзы
rus_verbs:сохранять{}, // сохранить данные в файл
rus_verbs:собирать{}, // собирать игрушки в ящик
rus_verbs:упаковывать{}, // упаковывать вещи в чемодан
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:стрельнуть{}, // стрельни в толпу!
rus_verbs:пулять{}, // пуляй в толпу
rus_verbs:пульнуть{}, // пульни в толпу
rus_verbs:становиться{}, // Становитесь в очередь.
rus_verbs:вписать{}, // Юля вписала свое имя в список.
rus_verbs:вписывать{}, // Мы вписывали свои имена в список
прилагательное:видный{}, // Планета Марс видна в обычный бинокль
rus_verbs:пойти{}, // Девочка рано пошла в школу
rus_verbs:отойти{}, // Эти обычаи отошли в историю.
rus_verbs:бить{}, // Холодный ветер бил ему в лицо.
rus_verbs:входить{}, // Это входит в его обязанности.
rus_verbs:принять{}, // меня приняли в пионеры
rus_verbs:уйти{}, // Правительство РФ ушло в отставку
rus_verbs:допустить{}, // Япония была допущена в Организацию Объединённых Наций в 1956 году.
rus_verbs:посвятить{}, // Я посвятил друга в свою тайну.
инфинитив:экспортировать{ вид:несоверш }, глагол:экспортировать{ вид:несоверш }, // экспортировать нефть в страны Востока
rus_verbs:взглянуть{}, // Я не смел взглянуть ему в глаза.
rus_verbs:идти{}, // Я иду гулять в парк.
rus_verbs:вскочить{}, // Я вскочил в трамвай и помчался в институт.
rus_verbs:получить{}, // Эту мебель мы получили в наследство от родителей.
rus_verbs:везти{}, // Учитель везёт детей в лагерь.
rus_verbs:качать{}, // Судно качает во все стороны.
rus_verbs:заезжать{}, // Сегодня вечером я заезжал в магазин за книгами.
rus_verbs:связать{}, // Свяжите свои вещи в узелок.
rus_verbs:пронести{}, // Пронесите стол в дверь.
rus_verbs:вынести{}, // Надо вынести примечания в конец.
rus_verbs:устроить{}, // Она устроила сына в школу.
rus_verbs:угодить{}, // Она угодила головой в дверь.
rus_verbs:отвернуться{}, // Она резко отвернулась в сторону.
rus_verbs:рассматривать{}, // Она рассматривала сцену в бинокль.
rus_verbs:обратить{}, // Война обратила город в развалины.
rus_verbs:сойтись{}, // Мы сошлись в школьные годы.
rus_verbs:приехать{}, // Мы приехали в положенный час.
rus_verbs:встать{}, // Дети встали в круг.
rus_verbs:впасть{}, // Из-за болезни он впал в нужду.
rus_verbs:придти{}, // придти в упадок
rus_verbs:заявить{}, // Надо заявить в милицию о краже.
rus_verbs:заявлять{}, // заявлять в полицию
rus_verbs:ехать{}, // Мы будем ехать в Орёл
rus_verbs:окрашиваться{}, // окрашиваться в красный цвет
rus_verbs:решить{}, // Дело решено в пользу истца.
rus_verbs:сесть{}, // Она села в кресло
rus_verbs:посмотреть{}, // Она посмотрела на себя в зеркало.
rus_verbs:влезать{}, // он влезает в мою квартирку
rus_verbs:попасться{}, // в мою ловушку попалась мышь
rus_verbs:лететь{}, // Мы летим в Орёл
ГЛ_ИНФ(брать), // он берет в свою правую руку очень тяжелый шершавый камень
ГЛ_ИНФ(взять), // Коля взял в руку камень
ГЛ_ИНФ(поехать), // поехать в круиз
ГЛ_ИНФ(подать), // подать в отставку
инфинитив:засыпать{ вид:соверш }, глагол:засыпать{ вид:соверш }, // засыпать песок в ящик
инфинитив:засыпать{ вид:несоверш переходность:переходный }, глагол:засыпать{ вид:несоверш переходность:переходный }, // засыпать песок в ящик
ГЛ_ИНФ(впадать), прилагательное:впадающий{}, прилагательное:впадавший{}, деепричастие:впадая{}, // впадать в море
ГЛ_ИНФ(постучать) // постучать в дверь
}
// Чтобы разрешить связывание в паттернах типа: уйти в BEA Systems
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_В_Вин предлог:в{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { глагол:подвывать{} предлог:в{} существительное:такт{ падеж:вин } }
then return true
}
#endregion Винительный
// Все остальные варианты по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:в{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:в{} * }
then return false,-5
}
#endregion Предлог_В
#region Предлог_НА
// ------------------- С ПРЕДЛОГОМ 'НА' ---------------------------
#region ПРЕДЛОЖНЫЙ
// НА+предложный падеж:
// ЛЕЖАТЬ НА СТОЛЕ
#region VerbList
wordentry_set Гл_НА_Предл=
{
rus_verbs:заслушать{}, // Вопрос заслушали на сессии облсовета
rus_verbs:ПРОСТУПАТЬ{}, // На лбу, носу и щеке проступало черное пятно кровоподтека. (ПРОСТУПАТЬ/ПРОСТУПИТЬ)
rus_verbs:ПРОСТУПИТЬ{}, //
rus_verbs:ВИДНЕТЬСЯ{}, // На другой стороне Океана виднелась полоска суши, окружавшая нижний ярус планеты. (ВИДНЕТЬСЯ)
rus_verbs:ЗАВИСАТЬ{}, // Машина умела зависать в воздухе на любой высоте (ЗАВИСАТЬ)
rus_verbs:ЗАМЕРЕТЬ{}, // Скользнув по траве, он замер на боку (ЗАМЕРЕТЬ, локатив)
rus_verbs:ЗАМИРАТЬ{}, //
rus_verbs:ЗАКРЕПИТЬ{}, // Он вручил ей лишний кинжал, который она воткнула в рубаху и закрепила на подоле. (ЗАКРЕПИТЬ)
rus_verbs:УПОЛЗТИ{}, // Зверь завизжал и попытался уползти на двух невредимых передних ногах. (УПОЛЗТИ/УПОЛЗАТЬ)
rus_verbs:УПОЛЗАТЬ{}, //
rus_verbs:БОЛТАТЬСЯ{}, // Тело его будет болтаться на пространственных ветрах, пока не сгниет веревка. (БОЛТАТЬСЯ)
rus_verbs:РАЗВЕРНУТЬ{}, // Филиппины разрешат США развернуть военные базы на своей территории (РАЗВЕРНУТЬ)
rus_verbs:ПОЛУЧИТЬ{}, // Я пытался узнать секреты и получить советы на официальном русскоязычном форуме (ПОЛУЧИТЬ)
rus_verbs:ЗАСИЯТЬ{}, // Он активировал управление, и на экране снова засияло изображение полумесяца. (ЗАСИЯТЬ)
rus_verbs:ВЗОРВАТЬСЯ{}, // Смертник взорвался на предвыборном митинге в Пакистане (ВЗОРВАТЬСЯ)
rus_verbs:искриться{},
rus_verbs:ОДЕРЖИВАТЬ{}, // На выборах в иранский парламент победу одерживают противники действующего президента (ОДЕРЖИВАТЬ)
rus_verbs:ПРЕСЕЧЬ{}, // На Украине пресекли дерзкий побег заключенных на вертолете (ПРЕСЕЧЬ)
rus_verbs:УЛЕТЕТЬ{}, // Голый норвежец улетел на лыжах с трамплина на 60 метров (УЛЕТЕТЬ)
rus_verbs:ПРОХОДИТЬ{}, // укрывающийся в лесу американский подросток проходил инициацию на охоте, выпив кружку крови первого убитого им оленя (ПРОХОДИТЬ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // На Марсе существовали условия для жизни (СУЩЕСТВОВАТЬ)
rus_verbs:УКАЗАТЬ{}, // Победу в Лиге чемпионов укажут на часах (УКАЗАТЬ)
rus_verbs:отвести{}, // отвести душу на людях
rus_verbs:сходиться{}, // Оба профессора сходились на том, что в черепной коробке динозавра
rus_verbs:сойтись{},
rus_verbs:ОБНАРУЖИТЬ{}, // Доказательство наличия подповерхностного океана на Европе обнаружено на её поверхности (ОБНАРУЖИТЬ)
rus_verbs:НАБЛЮДАТЬСЯ{}, // Редкий зодиакальный свет вскоре будет наблюдаться на ночном небе (НАБЛЮДАТЬСЯ)
rus_verbs:ДОСТИГНУТЬ{}, // На всех аварийных реакторах достигнуто состояние так называемой холодной остановки (ДОСТИГНУТЬ/ДОСТИЧЬ)
глагол:ДОСТИЧЬ{},
инфинитив:ДОСТИЧЬ{},
rus_verbs:завершить{}, // Российские биатлонисты завершили чемпионат мира на мажорной ноте
rus_verbs:РАСКЛАДЫВАТЬ{},
rus_verbs:ФОКУСИРОВАТЬСЯ{}, // Инвесторы предпочитают фокусироваться на среднесрочных ожиданиях (ФОКУСИРОВАТЬСЯ)
rus_verbs:ВОСПРИНИМАТЬ{}, // как несерьезно воспринимали его на выборах мэра (ВОСПРИНИМАТЬ)
rus_verbs:БУШЕВАТЬ{}, // на территории Тверской области бушевала гроза , в результате которой произошло отключение электроснабжения в ряде муниципальных образований региона (БУШЕВАТЬ)
rus_verbs:УЧАСТИТЬСЯ{}, // В последние месяцы в зоне ответственности бундесвера на севере Афганистана участились случаи обстрелов полевых лагерей немецких миротворцев (УЧАСТИТЬСЯ)
rus_verbs:ВЫИГРАТЬ{}, // Почему женская сборная России не может выиграть медаль на чемпионате мира (ВЫИГРАТЬ)
rus_verbs:ПРОПАСТЬ{}, // Пропавшим на прогулке актером заинтересовались следователи (ПРОПАСТЬ)
rus_verbs:УБИТЬ{}, // Силовики убили двух боевиков на административной границе Ингушетии и Чечни (УБИТЬ)
rus_verbs:подпрыгнуть{}, // кобель нелепо подпрыгнул на трех ногах , а его хозяин отправил струю пива мимо рта
rus_verbs:подпрыгивать{},
rus_verbs:высветиться{}, // на компьютере высветится твоя подпись
rus_verbs:фигурировать{}, // его портрет фигурирует на страницах печати и телеэкранах
rus_verbs:действовать{}, // выявленный контрабандный канал действовал на постоянной основе
rus_verbs:СОХРАНИТЬСЯ{}, // На рынке международных сделок IPO сохранится высокая активность (СОХРАНИТЬСЯ НА)
rus_verbs:ПРОЙТИ{}, // Необычный конкурс прошёл на севере Швеции (ПРОЙТИ НА предл)
rus_verbs:НАЧАТЬСЯ{}, // На северо-востоке США началась сильная снежная буря. (НАЧАТЬСЯ НА предл)
rus_verbs:ВОЗНИКНУТЬ{}, // Конфликт возник на почве совместной коммерческой деятельности по выращиванию овощей и зелени (ВОЗНИКНУТЬ НА)
rus_verbs:СВЕТИТЬСЯ{}, // она по-прежнему светится на лицах людей (СВЕТИТЬСЯ НА предл)
rus_verbs:ОРГАНИЗОВАТЬ{}, // Власти Москвы намерены организовать масленичные гуляния на 100 площадках (ОРГАНИЗОВАТЬ НА предл)
rus_verbs:ИМЕТЬ{}, // Имея власть на низовом уровне, оказывать самое непосредственное и определяющее влияние на верховную власть (ИМЕТЬ НА предл)
rus_verbs:ОПРОБОВАТЬ{}, // Опробовать и отточить этот инструмент на местных и региональных выборах (ОПРОБОВАТЬ, ОТТОЧИТЬ НА предл)
rus_verbs:ОТТОЧИТЬ{},
rus_verbs:ДОЛОЖИТЬ{}, // Участникам совещания предложено подготовить по этому вопросу свои предложения и доложить на повторной встрече (ДОЛОЖИТЬ НА предл)
rus_verbs:ОБРАЗОВЫВАТЬСЯ{}, // Солевые и пылевые бури , образующиеся на поверхности обнаженной площади моря , уничтожают урожаи и растительность (ОБРАЗОВЫВАТЬСЯ НА)
rus_verbs:СОБРАТЬ{}, // использует собранные на местном рынке депозиты (СОБРАТЬ НА предл)
инфинитив:НАХОДИТЬСЯ{ вид:несоверш}, // находившихся на борту самолета (НАХОДИТЬСЯ НА предл)
глагол:НАХОДИТЬСЯ{ вид:несоверш },
прилагательное:находившийся{ вид:несоверш },
прилагательное:находящийся{ вид:несоверш },
деепричастие:находясь{},
rus_verbs:ГОТОВИТЬ{}, // пищу готовят сами на примусах (ГОТОВИТЬ НА предл)
rus_verbs:РАЗДАТЬСЯ{}, // Они сообщили о сильном хлопке , который раздался на территории нефтебазы (РАЗДАТЬСЯ НА)
rus_verbs:ПОДСКАЛЬЗЫВАТЬСЯ{}, // подскальзываться на той же апельсиновой корке (ПОДСКАЛЬЗЫВАТЬСЯ НА)
rus_verbs:СКРЫТЬСЯ{}, // Германия: латвиец ограбил магазин и попытался скрыться на такси (СКРЫТЬСЯ НА предл)
rus_verbs:ВЫРАСТИТЬ{}, // Пациенту вырастили новый нос на руке (ВЫРАСТИТЬ НА)
rus_verbs:ПРОДЕМОНСТРИРОВАТЬ{}, // Они хотят подчеркнуть эмоциональную тонкость оппозиционера и на этом фоне продемонстрировать бездушность российской власти (ПРОДЕМОНСТРИРОВАТЬ НА предл)
rus_verbs:ОСУЩЕСТВЛЯТЬСЯ{}, // первичный анализ смеси запахов может осуществляться уже на уровне рецепторных нейронов благодаря механизму латерального торможения (ОСУЩЕСТВЛЯТЬСЯ НА)
rus_verbs:ВЫДЕЛЯТЬСЯ{}, // Ягоды брусники, резко выделяющиеся своим красным цветом на фоне зелёной листвы, поедаются животными и птицами (ВЫДЕЛЯТЬСЯ НА)
rus_verbs:РАСКРЫТЬ{}, // На Украине раскрыто крупное мошенничество в сфере туризма (РАСКРЫТЬ НА)
rus_verbs:ОБЖАРИВАТЬСЯ{}, // Омлет обжаривается на сливочном масле с одной стороны, пока он почти полностью не загустеет (ОБЖАРИВАТЬСЯ НА)
rus_verbs:ПРИГОТОВЛЯТЬ{}, // Яичница — блюдо европейской кухни, приготовляемое на сковороде из разбитых яиц (ПРИГОТОВЛЯТЬ НА)
rus_verbs:РАССАДИТЬ{}, // Женька рассадил игрушки на скамеечке (РАССАДИТЬ НА)
rus_verbs:ОБОЖДАТЬ{}, // обожди Анжелу на остановке троллейбуса (ОБОЖДАТЬ НА)
rus_verbs:УЧИТЬСЯ{}, // Марина учится на факультете журналистики (УЧИТЬСЯ НА предл)
rus_verbs:раскладываться{}, // Созревшие семенные экземпляры раскладывают на солнце или в теплом месте, где они делаются мягкими (РАСКЛАДЫВАТЬСЯ В, НА)
rus_verbs:ПОСЛУШАТЬ{}, // Послушайте друзей и врагов на расстоянии! (ПОСЛУШАТЬ НА)
rus_verbs:ВЕСТИСЬ{}, // На стороне противника всю ночь велась перегруппировка сил. (ВЕСТИСЬ НА)
rus_verbs:ПОИНТЕРЕСОВАТЬСЯ{}, // корреспондент поинтересовался у людей на улице (ПОИНТЕРЕСОВАТЬСЯ НА)
rus_verbs:ОТКРЫВАТЬСЯ{}, // Российские биржи открываются на негативном фоне (ОТКРЫВАТЬСЯ НА)
rus_verbs:СХОДИТЬ{}, // Вы сходите на следующей остановке? (СХОДИТЬ НА)
rus_verbs:ПОГИБНУТЬ{}, // Её отец погиб на войне. (ПОГИБНУТЬ НА)
rus_verbs:ВЫЙТИ{}, // Книга выйдет на будущей неделе. (ВЫЙТИ НА предл)
rus_verbs:НЕСТИСЬ{}, // Корабль несётся на всех парусах. (НЕСТИСЬ НА предл)
rus_verbs:вкалывать{}, // Папа вкалывает на работе, чтобы прокормить семью (вкалывать на)
rus_verbs:доказать{}, // разработчики доказали на практике применимость данного подхода к обсчету сцен (доказать на, применимость к)
rus_verbs:хулиганить{}, // дозволять кому-то хулиганить на кладбище (хулиганить на)
глагол:вычитать{вид:соверш}, инфинитив:вычитать{вид:соверш}, // вычитать на сайте (вычитать на сайте)
деепричастие:вычитав{},
rus_verbs:аккомпанировать{}, // он аккомпанировал певцу на губной гармошке (аккомпанировать на)
rus_verbs:набрать{}, // статья с заголовком, набранным на компьютере
rus_verbs:сделать{}, // книга с иллюстрацией, сделанной на компьютере
rus_verbs:развалиться{}, // Антонио развалился на диване
rus_verbs:улечься{}, // Антонио улегся на полу
rus_verbs:зарубить{}, // Заруби себе на носу.
rus_verbs:ценить{}, // Его ценят на заводе.
rus_verbs:вернуться{}, // Отец вернулся на закате.
rus_verbs:шить{}, // Вы умеете шить на машинке?
rus_verbs:бить{}, // Скот бьют на бойне.
rus_verbs:выехать{}, // Мы выехали на рассвете.
rus_verbs:валяться{}, // На полу валяется бумага.
rus_verbs:разложить{}, // она разложила полотенце на песке
rus_verbs:заниматься{}, // я занимаюсь на тренажере
rus_verbs:позаниматься{},
rus_verbs:порхать{}, // порхать на лугу
rus_verbs:пресекать{}, // пресекать на корню
rus_verbs:изъясняться{}, // изъясняться на непонятном языке
rus_verbs:развесить{}, // развесить на столбах
rus_verbs:обрасти{}, // обрасти на южной части
rus_verbs:откладываться{}, // откладываться на стенках артерий
rus_verbs:уносить{}, // уносить на носилках
rus_verbs:проплыть{}, // проплыть на плоту
rus_verbs:подъезжать{}, // подъезжать на повозках
rus_verbs:пульсировать{}, // пульсировать на лбу
rus_verbs:рассесться{}, // птицы расселись на ветках
rus_verbs:застопориться{}, // застопориться на первом пункте
rus_verbs:изловить{}, // изловить на окраинах
rus_verbs:покататься{}, // покататься на машинках
rus_verbs:залопотать{}, // залопотать на неизвестном языке
rus_verbs:растягивать{}, // растягивать на станке
rus_verbs:поделывать{}, // поделывать на пляже
rus_verbs:подстеречь{}, // подстеречь на площадке
rus_verbs:проектировать{}, // проектировать на компьютере
rus_verbs:притулиться{}, // притулиться на кушетке
rus_verbs:дозволять{}, // дозволять кому-то хулиганить на кладбище
rus_verbs:пострелять{}, // пострелять на испытательном полигоне
rus_verbs:засиживаться{}, // засиживаться на работе
rus_verbs:нежиться{}, // нежиться на солнышке
rus_verbs:притомиться{}, // притомиться на рабочем месте
rus_verbs:поселяться{}, // поселяться на чердаке
rus_verbs:потягиваться{}, // потягиваться на земле
rus_verbs:отлеживаться{}, // отлеживаться на койке
rus_verbs:протаранить{}, // протаранить на танке
rus_verbs:гарцевать{}, // гарцевать на коне
rus_verbs:облупиться{}, // облупиться на носу
rus_verbs:оговорить{}, // оговорить на собеседовании
rus_verbs:зарегистрироваться{}, // зарегистрироваться на сайте
rus_verbs:отпечатать{}, // отпечатать на картоне
rus_verbs:сэкономить{}, // сэкономить на мелочах
rus_verbs:покатать{}, // покатать на пони
rus_verbs:колесить{}, // колесить на старой машине
rus_verbs:понастроить{}, // понастроить на участках
rus_verbs:поджарить{}, // поджарить на костре
rus_verbs:узнаваться{}, // узнаваться на фотографии
rus_verbs:отощать{}, // отощать на казенных харчах
rus_verbs:редеть{}, // редеть на макушке
rus_verbs:оглашать{}, // оглашать на общем собрании
rus_verbs:лопотать{}, // лопотать на иврите
rus_verbs:пригреть{}, // пригреть на груди
rus_verbs:консультироваться{}, // консультироваться на форуме
rus_verbs:приноситься{}, // приноситься на одежде
rus_verbs:сушиться{}, // сушиться на балконе
rus_verbs:наследить{}, // наследить на полу
rus_verbs:нагреться{}, // нагреться на солнце
rus_verbs:рыбачить{}, // рыбачить на озере
rus_verbs:прокатить{}, // прокатить на выборах
rus_verbs:запинаться{}, // запинаться на ровном месте
rus_verbs:отрубиться{}, // отрубиться на мягкой подушке
rus_verbs:заморозить{}, // заморозить на улице
rus_verbs:промерзнуть{}, // промерзнуть на открытом воздухе
rus_verbs:просохнуть{}, // просохнуть на батарее
rus_verbs:развозить{}, // развозить на велосипеде
rus_verbs:прикорнуть{}, // прикорнуть на диванчике
rus_verbs:отпечататься{}, // отпечататься на коже
rus_verbs:выявлять{}, // выявлять на таможне
rus_verbs:расставлять{}, // расставлять на башнях
rus_verbs:прокрутить{}, // прокрутить на пальце
rus_verbs:умываться{}, // умываться на улице
rus_verbs:пересказывать{}, // пересказывать на страницах романа
rus_verbs:удалять{}, // удалять на пуховике
rus_verbs:хозяйничать{}, // хозяйничать на складе
rus_verbs:оперировать{}, // оперировать на поле боя
rus_verbs:поносить{}, // поносить на голове
rus_verbs:замурлыкать{}, // замурлыкать на коленях
rus_verbs:передвигать{}, // передвигать на тележке
rus_verbs:прочертить{}, // прочертить на земле
rus_verbs:колдовать{}, // колдовать на кухне
rus_verbs:отвозить{}, // отвозить на казенном транспорте
rus_verbs:трахать{}, // трахать на природе
rus_verbs:мастерить{}, // мастерить на кухне
rus_verbs:ремонтировать{}, // ремонтировать на коленке
rus_verbs:развезти{}, // развезти на велосипеде
rus_verbs:робеть{}, // робеть на сцене
инфинитив:реализовать{ вид:несоверш }, инфинитив:реализовать{ вид:соверш }, // реализовать на сайте
глагол:реализовать{ вид:несоверш }, глагол:реализовать{ вид:соверш },
деепричастие:реализовав{}, деепричастие:реализуя{},
rus_verbs:покаяться{}, // покаяться на смертном одре
rus_verbs:специализироваться{}, // специализироваться на тестировании
rus_verbs:попрыгать{}, // попрыгать на батуте
rus_verbs:переписывать{}, // переписывать на столе
rus_verbs:расписывать{}, // расписывать на доске
rus_verbs:зажимать{}, // зажимать на запястье
rus_verbs:практиковаться{}, // практиковаться на мышах
rus_verbs:уединиться{}, // уединиться на чердаке
rus_verbs:подохнуть{}, // подохнуть на чужбине
rus_verbs:приподниматься{}, // приподниматься на руках
rus_verbs:уродиться{}, // уродиться на полях
rus_verbs:продолжиться{}, // продолжиться на улице
rus_verbs:посапывать{}, // посапывать на диване
rus_verbs:ободрать{}, // ободрать на спине
rus_verbs:скрючиться{}, // скрючиться на песке
rus_verbs:тормознуть{}, // тормознуть на перекрестке
rus_verbs:лютовать{}, // лютовать на хуторе
rus_verbs:зарегистрировать{}, // зарегистрировать на сайте
rus_verbs:переждать{}, // переждать на вершине холма
rus_verbs:доминировать{}, // доминировать на территории
rus_verbs:публиковать{}, // публиковать на сайте
rus_verbs:морщить{}, // морщить на лбу
rus_verbs:сконцентрироваться{}, // сконцентрироваться на главном
rus_verbs:подрабатывать{}, // подрабатывать на рынке
rus_verbs:репетировать{}, // репетировать на заднем дворе
rus_verbs:подвернуть{}, // подвернуть на брусчатке
rus_verbs:зашелестеть{}, // зашелестеть на ветру
rus_verbs:расчесывать{}, // расчесывать на спине
rus_verbs:одевать{}, // одевать на рынке
rus_verbs:испечь{}, // испечь на углях
rus_verbs:сбрить{}, // сбрить на затылке
rus_verbs:согреться{}, // согреться на печке
rus_verbs:замаячить{}, // замаячить на горизонте
rus_verbs:пересчитывать{}, // пересчитывать на пальцах
rus_verbs:галдеть{}, // галдеть на крыльце
rus_verbs:переплыть{}, // переплыть на плоту
rus_verbs:передохнуть{}, // передохнуть на скамейке
rus_verbs:прижиться{}, // прижиться на ферме
rus_verbs:переправляться{}, // переправляться на плотах
rus_verbs:накупить{}, // накупить на блошином рынке
rus_verbs:проторчать{}, // проторчать на виду
rus_verbs:мокнуть{}, // мокнуть на улице
rus_verbs:застукать{}, // застукать на камбузе
rus_verbs:завязывать{}, // завязывать на ботинках
rus_verbs:повисать{}, // повисать на ветке
rus_verbs:подвизаться{}, // подвизаться на государственной службе
rus_verbs:кормиться{}, // кормиться на болоте
rus_verbs:покурить{}, // покурить на улице
rus_verbs:зимовать{}, // зимовать на болотах
rus_verbs:застегивать{}, // застегивать на гимнастерке
rus_verbs:поигрывать{}, // поигрывать на гитаре
rus_verbs:погореть{}, // погореть на махинациях с землей
rus_verbs:кувыркаться{}, // кувыркаться на батуте
rus_verbs:похрапывать{}, // похрапывать на диване
rus_verbs:пригревать{}, // пригревать на груди
rus_verbs:завязнуть{}, // завязнуть на болоте
rus_verbs:шастать{}, // шастать на втором этаже
rus_verbs:заночевать{}, // заночевать на сеновале
rus_verbs:отсиживаться{}, // отсиживаться на чердаке
rus_verbs:мчать{}, // мчать на байке
rus_verbs:сгнить{}, // сгнить на урановых рудниках
rus_verbs:тренировать{}, // тренировать на манекенах
rus_verbs:повеселиться{}, // повеселиться на празднике
rus_verbs:измучиться{}, // измучиться на болоте
rus_verbs:увянуть{}, // увянуть на подоконнике
rus_verbs:раскрутить{}, // раскрутить на оси
rus_verbs:выцвести{}, // выцвести на солнечном свету
rus_verbs:изготовлять{}, // изготовлять на коленке
rus_verbs:гнездиться{}, // гнездиться на вершине дерева
rus_verbs:разогнаться{}, // разогнаться на мотоцикле
rus_verbs:излагаться{}, // излагаться на страницах доклада
rus_verbs:сконцентрировать{}, // сконцентрировать на левом фланге
rus_verbs:расчесать{}, // расчесать на макушке
rus_verbs:плавиться{}, // плавиться на солнце
rus_verbs:редактировать{}, // редактировать на ноутбуке
rus_verbs:подскакивать{}, // подскакивать на месте
rus_verbs:покупаться{}, // покупаться на рынке
rus_verbs:промышлять{}, // промышлять на мелководье
rus_verbs:приобретаться{}, // приобретаться на распродажах
rus_verbs:наигрывать{}, // наигрывать на банджо
rus_verbs:маневрировать{}, // маневрировать на флангах
rus_verbs:запечатлеться{}, // запечатлеться на записях камер
rus_verbs:укрывать{}, // укрывать на чердаке
rus_verbs:подорваться{}, // подорваться на фугасе
rus_verbs:закрепиться{}, // закрепиться на занятых позициях
rus_verbs:громыхать{}, // громыхать на кухне
инфинитив:подвигаться{ вид:соверш }, глагол:подвигаться{ вид:соверш }, // подвигаться на полу
деепричастие:подвигавшись{},
rus_verbs:добываться{}, // добываться на территории Анголы
rus_verbs:приплясывать{}, // приплясывать на сцене
rus_verbs:доживать{}, // доживать на больничной койке
rus_verbs:отпраздновать{}, // отпраздновать на работе
rus_verbs:сгубить{}, // сгубить на корню
rus_verbs:схоронить{}, // схоронить на кладбище
rus_verbs:тускнеть{}, // тускнеть на солнце
rus_verbs:скопить{}, // скопить на счету
rus_verbs:помыть{}, // помыть на своем этаже
rus_verbs:пороть{}, // пороть на конюшне
rus_verbs:наличествовать{}, // наличествовать на складе
rus_verbs:нащупывать{}, // нащупывать на полке
rus_verbs:змеиться{}, // змеиться на дне
rus_verbs:пожелтеть{}, // пожелтеть на солнце
rus_verbs:заостриться{}, // заостриться на конце
rus_verbs:свезти{}, // свезти на поле
rus_verbs:прочувствовать{}, // прочувствовать на своей шкуре
rus_verbs:подкрутить{}, // подкрутить на приборной панели
rus_verbs:рубиться{}, // рубиться на мечах
rus_verbs:сиживать{}, // сиживать на крыльце
rus_verbs:тараторить{}, // тараторить на иностранном языке
rus_verbs:теплеть{}, // теплеть на сердце
rus_verbs:покачаться{}, // покачаться на ветке
rus_verbs:сосредоточиваться{}, // сосредоточиваться на главной задаче
rus_verbs:развязывать{}, // развязывать на ботинках
rus_verbs:подвозить{}, // подвозить на мотороллере
rus_verbs:вышивать{}, // вышивать на рубашке
rus_verbs:скупать{}, // скупать на открытом рынке
rus_verbs:оформлять{}, // оформлять на встрече
rus_verbs:распускаться{}, // распускаться на клумбах
rus_verbs:прогореть{}, // прогореть на спекуляциях
rus_verbs:приползти{}, // приползти на коленях
rus_verbs:загореть{}, // загореть на пляже
rus_verbs:остудить{}, // остудить на балконе
rus_verbs:нарвать{}, // нарвать на поляне
rus_verbs:издохнуть{}, // издохнуть на болоте
rus_verbs:разгружать{}, // разгружать на дороге
rus_verbs:произрастать{}, // произрастать на болотах
rus_verbs:разуться{}, // разуться на коврике
rus_verbs:сооружать{}, // сооружать на площади
rus_verbs:зачитывать{}, // зачитывать на митинге
rus_verbs:уместиться{}, // уместиться на ладони
rus_verbs:закупить{}, // закупить на рынке
rus_verbs:горланить{}, // горланить на улице
rus_verbs:экономить{}, // экономить на спичках
rus_verbs:исправлять{}, // исправлять на доске
rus_verbs:расслабляться{}, // расслабляться на лежаке
rus_verbs:скапливаться{}, // скапливаться на крыше
rus_verbs:сплетничать{}, // сплетничать на скамеечке
rus_verbs:отъезжать{}, // отъезжать на лимузине
rus_verbs:отчитывать{}, // отчитывать на собрании
rus_verbs:сфокусировать{}, // сфокусировать на удаленной точке
rus_verbs:потчевать{}, // потчевать на лаврах
rus_verbs:окопаться{}, // окопаться на окраине
rus_verbs:загорать{}, // загорать на пляже
rus_verbs:обгореть{}, // обгореть на солнце
rus_verbs:распознавать{}, // распознавать на фотографии
rus_verbs:заплетаться{}, // заплетаться на макушке
rus_verbs:перегреться{}, // перегреться на жаре
rus_verbs:подметать{}, // подметать на крыльце
rus_verbs:нарисоваться{}, // нарисоваться на горизонте
rus_verbs:проскакивать{}, // проскакивать на экране
rus_verbs:попивать{}, // попивать на балконе чай
rus_verbs:отплывать{}, // отплывать на лодке
rus_verbs:чирикать{}, // чирикать на ветках
rus_verbs:скупить{}, // скупить на оптовых базах
rus_verbs:наколоть{}, // наколоть на коже картинку
rus_verbs:созревать{}, // созревать на ветке
rus_verbs:проколоться{}, // проколоться на мелочи
rus_verbs:крутнуться{}, // крутнуться на заднем колесе
rus_verbs:переночевать{}, // переночевать на постоялом дворе
rus_verbs:концентрироваться{}, // концентрироваться на фильтре
rus_verbs:одичать{}, // одичать на хуторе
rus_verbs:спасаться{}, // спасаются на лодке
rus_verbs:доказываться{}, // доказываться на страницах книги
rus_verbs:познаваться{}, // познаваться на ринге
rus_verbs:замыкаться{}, // замыкаться на металлическом предмете
rus_verbs:заприметить{}, // заприметить на пригорке
rus_verbs:продержать{}, // продержать на морозе
rus_verbs:форсировать{}, // форсировать на плотах
rus_verbs:сохнуть{}, // сохнуть на солнце
rus_verbs:выявить{}, // выявить на поверхности
rus_verbs:заседать{}, // заседать на кафедре
rus_verbs:расплачиваться{}, // расплачиваться на выходе
rus_verbs:светлеть{}, // светлеть на горизонте
rus_verbs:залепетать{}, // залепетать на незнакомом языке
rus_verbs:подсчитывать{}, // подсчитывать на пальцах
rus_verbs:зарыть{}, // зарыть на пустыре
rus_verbs:сформироваться{}, // сформироваться на месте
rus_verbs:развертываться{}, // развертываться на площадке
rus_verbs:набивать{}, // набивать на манекенах
rus_verbs:замерзать{}, // замерзать на ветру
rus_verbs:схватывать{}, // схватывать на лету
rus_verbs:перевестись{}, // перевестись на Руси
rus_verbs:смешивать{}, // смешивать на блюдце
rus_verbs:прождать{}, // прождать на входе
rus_verbs:мерзнуть{}, // мерзнуть на ветру
rus_verbs:растирать{}, // растирать на коже
rus_verbs:переспать{}, // переспал на сеновале
rus_verbs:рассекать{}, // рассекать на скутере
rus_verbs:опровергнуть{}, // опровергнуть на высшем уровне
rus_verbs:дрыхнуть{}, // дрыхнуть на диване
rus_verbs:распять{}, // распять на кресте
rus_verbs:запечься{}, // запечься на костре
rus_verbs:застилать{}, // застилать на балконе
rus_verbs:сыскаться{}, // сыскаться на огороде
rus_verbs:разориться{}, // разориться на продаже спичек
rus_verbs:переделать{}, // переделать на станке
rus_verbs:разъяснять{}, // разъяснять на страницах газеты
rus_verbs:поседеть{}, // поседеть на висках
rus_verbs:протащить{}, // протащить на спине
rus_verbs:осуществиться{}, // осуществиться на деле
rus_verbs:селиться{}, // селиться на окраине
rus_verbs:оплачивать{}, // оплачивать на первой кассе
rus_verbs:переворачивать{}, // переворачивать на сковородке
rus_verbs:упражняться{}, // упражняться на батуте
rus_verbs:испробовать{}, // испробовать на себе
rus_verbs:разгладиться{}, // разгладиться на спине
rus_verbs:рисоваться{}, // рисоваться на стекле
rus_verbs:продрогнуть{}, // продрогнуть на морозе
rus_verbs:пометить{}, // пометить на доске
rus_verbs:приютить{}, // приютить на чердаке
rus_verbs:избирать{}, // избирать на первых свободных выборах
rus_verbs:затеваться{}, // затеваться на матче
rus_verbs:уплывать{}, // уплывать на катере
rus_verbs:замерцать{}, // замерцать на рекламном щите
rus_verbs:фиксироваться{}, // фиксироваться на достигнутом уровне
rus_verbs:запираться{}, // запираться на чердаке
rus_verbs:загубить{}, // загубить на корню
rus_verbs:развеяться{}, // развеяться на природе
rus_verbs:съезжаться{}, // съезжаться на лимузинах
rus_verbs:потанцевать{}, // потанцевать на могиле
rus_verbs:дохнуть{}, // дохнуть на солнце
rus_verbs:припарковаться{}, // припарковаться на газоне
rus_verbs:отхватить{}, // отхватить на распродаже
rus_verbs:остывать{}, // остывать на улице
rus_verbs:переваривать{}, // переваривать на высокой ветке
rus_verbs:подвесить{}, // подвесить на веревке
rus_verbs:хвастать{}, // хвастать на работе
rus_verbs:отрабатывать{}, // отрабатывать на уборке урожая
rus_verbs:разлечься{}, // разлечься на полу
rus_verbs:очертить{}, // очертить на полу
rus_verbs:председательствовать{}, // председательствовать на собрании
rus_verbs:сконфузиться{}, // сконфузиться на сцене
rus_verbs:выявляться{}, // выявляться на ринге
rus_verbs:крутануться{}, // крутануться на заднем колесе
rus_verbs:караулить{}, // караулить на входе
rus_verbs:перечислять{}, // перечислять на пальцах
rus_verbs:обрабатывать{}, // обрабатывать на станке
rus_verbs:настигать{}, // настигать на берегу
rus_verbs:разгуливать{}, // разгуливать на берегу
rus_verbs:насиловать{}, // насиловать на пляже
rus_verbs:поредеть{}, // поредеть на макушке
rus_verbs:учитывать{}, // учитывать на балансе
rus_verbs:зарождаться{}, // зарождаться на большой глубине
rus_verbs:распространять{}, // распространять на сайтах
rus_verbs:пировать{}, // пировать на вершине холма
rus_verbs:начертать{}, // начертать на стене
rus_verbs:расцветать{}, // расцветать на подоконнике
rus_verbs:умнеть{}, // умнеть на глазах
rus_verbs:царствовать{}, // царствовать на окраине
rus_verbs:закрутиться{}, // закрутиться на работе
rus_verbs:отработать{}, // отработать на шахте
rus_verbs:полечь{}, // полечь на поле брани
rus_verbs:щебетать{}, // щебетать на ветке
rus_verbs:подчеркиваться{}, // подчеркиваться на сайте
rus_verbs:посеять{}, // посеять на другом поле
rus_verbs:замечаться{}, // замечаться на пастбище
rus_verbs:просчитать{}, // просчитать на пальцах
rus_verbs:голосовать{}, // голосовать на трассе
rus_verbs:маяться{}, // маяться на пляже
rus_verbs:сколотить{}, // сколотить на службе
rus_verbs:обретаться{}, // обретаться на чужбине
rus_verbs:обливаться{}, // обливаться на улице
rus_verbs:катать{}, // катать на лошадке
rus_verbs:припрятать{}, // припрятать на теле
rus_verbs:запаниковать{}, // запаниковать на экзамене
инфинитив:слетать{ вид:соверш }, глагол:слетать{ вид:соверш }, // слетать на частном самолете
деепричастие:слетав{},
rus_verbs:срубить{}, // срубить денег на спекуляциях
rus_verbs:зажигаться{}, // зажигаться на улице
rus_verbs:жарить{}, // жарить на углях
rus_verbs:накапливаться{}, // накапливаться на счету
rus_verbs:распуститься{}, // распуститься на грядке
rus_verbs:рассаживаться{}, // рассаживаться на местах
rus_verbs:странствовать{}, // странствовать на лошади
rus_verbs:осматриваться{}, // осматриваться на месте
rus_verbs:разворачивать{}, // разворачивать на завоеванной территории
rus_verbs:согревать{}, // согревать на вершине горы
rus_verbs:заскучать{}, // заскучать на вахте
rus_verbs:перекусить{}, // перекусить на бегу
rus_verbs:приплыть{}, // приплыть на тримаране
rus_verbs:зажигать{}, // зажигать на танцах
rus_verbs:закопать{}, // закопать на поляне
rus_verbs:стирать{}, // стирать на берегу
rus_verbs:подстерегать{}, // подстерегать на подходе
rus_verbs:погулять{}, // погулять на свадьбе
rus_verbs:огласить{}, // огласить на митинге
rus_verbs:разбогатеть{}, // разбогатеть на прииске
rus_verbs:грохотать{}, // грохотать на чердаке
rus_verbs:расположить{}, // расположить на границе
rus_verbs:реализоваться{}, // реализоваться на новой работе
rus_verbs:застывать{}, // застывать на морозе
rus_verbs:запечатлеть{}, // запечатлеть на пленке
rus_verbs:тренироваться{}, // тренироваться на манекене
rus_verbs:поспорить{}, // поспорить на совещании
rus_verbs:затягивать{}, // затягивать на поясе
rus_verbs:зиждиться{}, // зиждиться на твердой основе
rus_verbs:построиться{}, // построиться на песке
rus_verbs:надрываться{}, // надрываться на работе
rus_verbs:закипать{}, // закипать на плите
rus_verbs:затонуть{}, // затонуть на мелководье
rus_verbs:побыть{}, // побыть на фазенде
rus_verbs:сгорать{}, // сгорать на солнце
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на улице
деепричастие:пописав{ aux stress="поп^исав" },
rus_verbs:подраться{}, // подраться на сцене
rus_verbs:заправить{}, // заправить на последней заправке
rus_verbs:обозначаться{}, // обозначаться на карте
rus_verbs:просиживать{}, // просиживать на берегу
rus_verbs:начертить{}, // начертить на листке
rus_verbs:тормозить{}, // тормозить на льду
rus_verbs:затевать{}, // затевать на космической базе
rus_verbs:задерживать{}, // задерживать на таможне
rus_verbs:прилетать{}, // прилетать на частном самолете
rus_verbs:полулежать{}, // полулежать на травке
rus_verbs:ерзать{}, // ерзать на табуретке
rus_verbs:покопаться{}, // покопаться на складе
rus_verbs:подвезти{}, // подвезти на машине
rus_verbs:полежать{}, // полежать на водном матрасе
rus_verbs:стыть{}, // стыть на улице
rus_verbs:стынуть{}, // стынуть на улице
rus_verbs:скреститься{}, // скреститься на груди
rus_verbs:припарковать{}, // припарковать на стоянке
rus_verbs:здороваться{}, // здороваться на кафедре
rus_verbs:нацарапать{}, // нацарапать на парте
rus_verbs:откопать{}, // откопать на поляне
rus_verbs:смастерить{}, // смастерить на коленках
rus_verbs:довезти{}, // довезти на машине
rus_verbs:избивать{}, // избивать на крыше
rus_verbs:сварить{}, // сварить на костре
rus_verbs:истребить{}, // истребить на корню
rus_verbs:раскопать{}, // раскопать на болоте
rus_verbs:попить{}, // попить на кухне
rus_verbs:заправлять{}, // заправлять на базе
rus_verbs:кушать{}, // кушать на кухне
rus_verbs:замолкать{}, // замолкать на половине фразы
rus_verbs:измеряться{}, // измеряться на весах
rus_verbs:сбываться{}, // сбываться на самом деле
rus_verbs:изображаться{}, // изображается на сцене
rus_verbs:фиксировать{}, // фиксировать на данной высоте
rus_verbs:ослаблять{}, // ослаблять на шее
rus_verbs:зреть{}, // зреть на грядке
rus_verbs:зеленеть{}, // зеленеть на грядке
rus_verbs:критиковать{}, // критиковать на страницах газеты
rus_verbs:облететь{}, // облететь на самолете
rus_verbs:заразиться{}, // заразиться на работе
rus_verbs:рассеять{}, // рассеять на территории
rus_verbs:печься{}, // печься на костре
rus_verbs:поспать{}, // поспать на земле
rus_verbs:сплетаться{}, // сплетаться на макушке
rus_verbs:удерживаться{}, // удерживаться на расстоянии
rus_verbs:помешаться{}, // помешаться на чистоте
rus_verbs:ликвидировать{}, // ликвидировать на полигоне
rus_verbs:проваляться{}, // проваляться на диване
rus_verbs:лечиться{}, // лечиться на дому
rus_verbs:обработать{}, // обработать на станке
rus_verbs:защелкнуть{}, // защелкнуть на руках
rus_verbs:разносить{}, // разносить на одежде
rus_verbs:чесать{}, // чесать на груди
rus_verbs:наладить{}, // наладить на конвейере выпуск
rus_verbs:отряхнуться{}, // отряхнуться на улице
rus_verbs:разыгрываться{}, // разыгрываться на скачках
rus_verbs:обеспечиваться{}, // обеспечиваться на выгодных условиях
rus_verbs:греться{}, // греться на вокзале
rus_verbs:засидеться{}, // засидеться на одном месте
rus_verbs:материализоваться{}, // материализоваться на границе
rus_verbs:рассеиваться{}, // рассеиваться на высоте вершин
rus_verbs:перевозить{}, // перевозить на платформе
rus_verbs:поиграть{}, // поиграть на скрипке
rus_verbs:потоптаться{}, // потоптаться на одном месте
rus_verbs:переправиться{}, // переправиться на плоту
rus_verbs:забрезжить{}, // забрезжить на горизонте
rus_verbs:завывать{}, // завывать на опушке
rus_verbs:заваривать{}, // заваривать на кухоньке
rus_verbs:перемещаться{}, // перемещаться на спасательном плоту
инфинитив:писаться{ aux stress="пис^аться" }, глагол:писаться{ aux stress="пис^аться" }, // писаться на бланке
rus_verbs:праздновать{}, // праздновать на улицах
rus_verbs:обучить{}, // обучить на корте
rus_verbs:орудовать{}, // орудовать на складе
rus_verbs:подрасти{}, // подрасти на глядке
rus_verbs:шелестеть{}, // шелестеть на ветру
rus_verbs:раздеваться{}, // раздеваться на публике
rus_verbs:пообедать{}, // пообедать на газоне
rus_verbs:жрать{}, // жрать на помойке
rus_verbs:исполняться{}, // исполняться на флейте
rus_verbs:похолодать{}, // похолодать на улице
rus_verbs:гнить{}, // гнить на каторге
rus_verbs:прослушать{}, // прослушать на концерте
rus_verbs:совещаться{}, // совещаться на заседании
rus_verbs:покачивать{}, // покачивать на волнах
rus_verbs:отсидеть{}, // отсидеть на гаупвахте
rus_verbs:формировать{}, // формировать на секретной базе
rus_verbs:захрапеть{}, // захрапеть на кровати
rus_verbs:объехать{}, // объехать на попутке
rus_verbs:поселить{}, // поселить на верхних этажах
rus_verbs:заворочаться{}, // заворочаться на сене
rus_verbs:напрятать{}, // напрятать на теле
rus_verbs:очухаться{}, // очухаться на земле
rus_verbs:полистать{}, // полистать на досуге
rus_verbs:завертеть{}, // завертеть на шесте
rus_verbs:печатать{}, // печатать на ноуте
rus_verbs:отыскаться{}, // отыскаться на складе
rus_verbs:зафиксировать{}, // зафиксировать на пленке
rus_verbs:расстилаться{}, // расстилаться на столе
rus_verbs:заместить{}, // заместить на посту
rus_verbs:угасать{}, // угасать на неуправляемом корабле
rus_verbs:сразить{}, // сразить на ринге
rus_verbs:расплываться{}, // расплываться на жаре
rus_verbs:сосчитать{}, // сосчитать на пальцах
rus_verbs:сгуститься{}, // сгуститься на небольшой высоте
rus_verbs:цитировать{}, // цитировать на плите
rus_verbs:ориентироваться{}, // ориентироваться на местности
rus_verbs:расширить{}, // расширить на другом конце
rus_verbs:обтереть{}, // обтереть на стоянке
rus_verbs:подстрелить{}, // подстрелить на охоте
rus_verbs:растереть{}, // растереть на твердой поверхности
rus_verbs:подавлять{}, // подавлять на первом этапе
rus_verbs:смешиваться{}, // смешиваться на поверхности
// инфинитив:вычитать{ aux stress="в^ычитать" }, глагол:вычитать{ aux stress="в^ычитать" }, // вычитать на сайте
// деепричастие:вычитав{},
rus_verbs:сократиться{}, // сократиться на втором этапе
rus_verbs:занервничать{}, // занервничать на экзамене
rus_verbs:соприкоснуться{}, // соприкоснуться на трассе
rus_verbs:обозначить{}, // обозначить на плане
rus_verbs:обучаться{}, // обучаться на производстве
rus_verbs:снизиться{}, // снизиться на большой высоте
rus_verbs:простудиться{}, // простудиться на ветру
rus_verbs:поддерживаться{}, // поддерживается на встрече
rus_verbs:уплыть{}, // уплыть на лодочке
rus_verbs:резвиться{}, // резвиться на песочке
rus_verbs:поерзать{}, // поерзать на скамеечке
rus_verbs:похвастаться{}, // похвастаться на встрече
rus_verbs:знакомиться{}, // знакомиться на уроке
rus_verbs:проплывать{}, // проплывать на катере
rus_verbs:засесть{}, // засесть на чердаке
rus_verbs:подцепить{}, // подцепить на дискотеке
rus_verbs:обыскать{}, // обыскать на входе
rus_verbs:оправдаться{}, // оправдаться на суде
rus_verbs:раскрываться{}, // раскрываться на сцене
rus_verbs:одеваться{}, // одеваться на вещевом рынке
rus_verbs:засветиться{}, // засветиться на фотографиях
rus_verbs:употребляться{}, // употребляться на птицефабриках
rus_verbs:грабить{}, // грабить на пустыре
rus_verbs:гонять{}, // гонять на повышенных оборотах
rus_verbs:развеваться{}, // развеваться на древке
rus_verbs:основываться{}, // основываться на безусловных фактах
rus_verbs:допрашивать{}, // допрашивать на базе
rus_verbs:проработать{}, // проработать на стройке
rus_verbs:сосредоточить{}, // сосредоточить на месте
rus_verbs:сочинять{}, // сочинять на ходу
rus_verbs:ползать{}, // ползать на камне
rus_verbs:раскинуться{}, // раскинуться на пустыре
rus_verbs:уставать{}, // уставать на работе
rus_verbs:укрепить{}, // укрепить на конце
rus_verbs:образовывать{}, // образовывать на открытом воздухе взрывоопасную смесь
rus_verbs:одобрять{}, // одобрять на словах
rus_verbs:приговорить{}, // приговорить на заседании тройки
rus_verbs:чернеть{}, // чернеть на свету
rus_verbs:гнуть{}, // гнуть на станке
rus_verbs:размещаться{}, // размещаться на бирже
rus_verbs:соорудить{}, // соорудить на даче
rus_verbs:пастись{}, // пастись на лугу
rus_verbs:формироваться{}, // формироваться на дне
rus_verbs:таить{}, // таить на дне
rus_verbs:приостановиться{}, // приостановиться на середине
rus_verbs:топтаться{}, // топтаться на месте
rus_verbs:громить{}, // громить на подступах
rus_verbs:вычислить{}, // вычислить на бумажке
rus_verbs:заказывать{}, // заказывать на сайте
rus_verbs:осуществить{}, // осуществить на практике
rus_verbs:обосноваться{}, // обосноваться на верхушке
rus_verbs:пытать{}, // пытать на электрическом стуле
rus_verbs:совершиться{}, // совершиться на заседании
rus_verbs:свернуться{}, // свернуться на медленном огне
rus_verbs:пролетать{}, // пролетать на дельтаплане
rus_verbs:сбыться{}, // сбыться на самом деле
rus_verbs:разговориться{}, // разговориться на уроке
rus_verbs:разворачиваться{}, // разворачиваться на перекрестке
rus_verbs:преподнести{}, // преподнести на блюдечке
rus_verbs:напечатать{}, // напечатать на лазернике
rus_verbs:прорвать{}, // прорвать на периферии
rus_verbs:раскачиваться{}, // раскачиваться на доске
rus_verbs:задерживаться{}, // задерживаться на старте
rus_verbs:угощать{}, // угощать на вечеринке
rus_verbs:шарить{}, // шарить на столе
rus_verbs:увеличивать{}, // увеличивать на первом этапе
rus_verbs:рехнуться{}, // рехнуться на старости лет
rus_verbs:расцвести{}, // расцвести на грядке
rus_verbs:закипеть{}, // закипеть на плите
rus_verbs:подлететь{}, // подлететь на параплане
rus_verbs:рыться{}, // рыться на свалке
rus_verbs:добираться{}, // добираться на попутках
rus_verbs:продержаться{}, // продержаться на вершине
rus_verbs:разыскивать{}, // разыскивать на выставках
rus_verbs:освобождать{}, // освобождать на заседании
rus_verbs:передвигаться{}, // передвигаться на самокате
rus_verbs:проявиться{}, // проявиться на свету
rus_verbs:заскользить{}, // заскользить на льду
rus_verbs:пересказать{}, // пересказать на сцене студенческого театра
rus_verbs:протестовать{}, // протестовать на улице
rus_verbs:указываться{}, // указываться на табличках
rus_verbs:прискакать{}, // прискакать на лошадке
rus_verbs:копошиться{}, // копошиться на свежем воздухе
rus_verbs:подсчитать{}, // подсчитать на бумажке
rus_verbs:разволноваться{}, // разволноваться на экзамене
rus_verbs:завертеться{}, // завертеться на полу
rus_verbs:ознакомиться{}, // ознакомиться на ходу
rus_verbs:ржать{}, // ржать на уроке
rus_verbs:раскинуть{}, // раскинуть на грядках
rus_verbs:разгромить{}, // разгромить на ринге
rus_verbs:подслушать{}, // подслушать на совещании
rus_verbs:описываться{}, // описываться на страницах книги
rus_verbs:качаться{}, // качаться на стуле
rus_verbs:усилить{}, // усилить на флангах
rus_verbs:набросать{}, // набросать на клочке картона
rus_verbs:расстреливать{}, // расстреливать на подходе
rus_verbs:запрыгать{}, // запрыгать на одной ноге
rus_verbs:сыскать{}, // сыскать на чужбине
rus_verbs:подтвердиться{}, // подтвердиться на практике
rus_verbs:плескаться{}, // плескаться на мелководье
rus_verbs:расширяться{}, // расширяться на конце
rus_verbs:подержать{}, // подержать на солнце
rus_verbs:планироваться{}, // планироваться на общем собрании
rus_verbs:сгинуть{}, // сгинуть на чужбине
rus_verbs:замкнуться{}, // замкнуться на точке
rus_verbs:закачаться{}, // закачаться на ветру
rus_verbs:перечитывать{}, // перечитывать на ходу
rus_verbs:перелететь{}, // перелететь на дельтаплане
rus_verbs:оживать{}, // оживать на солнце
rus_verbs:женить{}, // женить на богатой невесте
rus_verbs:заглохнуть{}, // заглохнуть на старте
rus_verbs:копаться{}, // копаться на полу
rus_verbs:развлекаться{}, // развлекаться на дискотеке
rus_verbs:печататься{}, // печататься на струйном принтере
rus_verbs:обрываться{}, // обрываться на полуслове
rus_verbs:ускакать{}, // ускакать на лошадке
rus_verbs:подписывать{}, // подписывать на столе
rus_verbs:добывать{}, // добывать на выработке
rus_verbs:скопиться{}, // скопиться на выходе
rus_verbs:повстречать{}, // повстречать на пути
rus_verbs:поцеловаться{}, // поцеловаться на площади
rus_verbs:растянуть{}, // растянуть на столе
rus_verbs:подаваться{}, // подаваться на благотворительном обеде
rus_verbs:повстречаться{}, // повстречаться на митинге
rus_verbs:примоститься{}, // примоститься на ступеньках
rus_verbs:отразить{}, // отразить на страницах доклада
rus_verbs:пояснять{}, // пояснять на страницах приложения
rus_verbs:накормить{}, // накормить на кухне
rus_verbs:поужинать{}, // поужинать на веранде
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть на митинге
деепричастие:спев{},
инфинитив:спеть{ вид:несоверш }, глагол:спеть{ вид:несоверш },
rus_verbs:топить{}, // топить на мелководье
rus_verbs:освоить{}, // освоить на практике
rus_verbs:распластаться{}, // распластаться на травке
rus_verbs:отплыть{}, // отплыть на старом каяке
rus_verbs:улетать{}, // улетать на любом самолете
rus_verbs:отстаивать{}, // отстаивать на корте
rus_verbs:осуждать{}, // осуждать на словах
rus_verbs:переговорить{}, // переговорить на обеде
rus_verbs:укрыть{}, // укрыть на чердаке
rus_verbs:томиться{}, // томиться на привязи
rus_verbs:сжигать{}, // сжигать на полигоне
rus_verbs:позавтракать{}, // позавтракать на лоне природы
rus_verbs:функционировать{}, // функционирует на солнечной энергии
rus_verbs:разместить{}, // разместить на сайте
rus_verbs:пронести{}, // пронести на теле
rus_verbs:нашарить{}, // нашарить на столе
rus_verbs:корчиться{}, // корчиться на полу
rus_verbs:распознать{}, // распознать на снимке
rus_verbs:повеситься{}, // повеситься на шнуре
rus_verbs:обозначиться{}, // обозначиться на картах
rus_verbs:оступиться{}, // оступиться на скользком льду
rus_verbs:подносить{}, // подносить на блюдечке
rus_verbs:расстелить{}, // расстелить на газоне
rus_verbs:обсуждаться{}, // обсуждаться на собрании
rus_verbs:расписаться{}, // расписаться на бланке
rus_verbs:плестись{}, // плестись на привязи
rus_verbs:объявиться{}, // объявиться на сцене
rus_verbs:повышаться{}, // повышаться на первом датчике
rus_verbs:разрабатывать{}, // разрабатывать на заводе
rus_verbs:прерывать{}, // прерывать на середине
rus_verbs:каяться{}, // каяться на публике
rus_verbs:освоиться{}, // освоиться на лошади
rus_verbs:подплыть{}, // подплыть на плоту
rus_verbs:оскорбить{}, // оскорбить на митинге
rus_verbs:торжествовать{}, // торжествовать на пьедестале
rus_verbs:поправлять{}, // поправлять на одежде
rus_verbs:отражать{}, // отражать на картине
rus_verbs:дремать{}, // дремать на кушетке
rus_verbs:применяться{}, // применяться на производстве стали
rus_verbs:поражать{}, // поражать на большой дистанции
rus_verbs:расстрелять{}, // расстрелять на окраине хутора
rus_verbs:рассчитать{}, // рассчитать на калькуляторе
rus_verbs:записывать{}, // записывать на ленте
rus_verbs:перебирать{}, // перебирать на ладони
rus_verbs:разбиться{}, // разбиться на катере
rus_verbs:поискать{}, // поискать на ферме
rus_verbs:прятать{}, // прятать на заброшенном складе
rus_verbs:пропеть{}, // пропеть на эстраде
rus_verbs:замелькать{}, // замелькать на экране
rus_verbs:грустить{}, // грустить на веранде
rus_verbs:крутить{}, // крутить на оси
rus_verbs:подготовить{}, // подготовить на конспиративной квартире
rus_verbs:различать{}, // различать на картинке
rus_verbs:киснуть{}, // киснуть на чужбине
rus_verbs:оборваться{}, // оборваться на полуслове
rus_verbs:запутаться{}, // запутаться на простейшем тесте
rus_verbs:общаться{}, // общаться на уроке
rus_verbs:производиться{}, // производиться на фабрике
rus_verbs:сочинить{}, // сочинить на досуге
rus_verbs:давить{}, // давить на лице
rus_verbs:разработать{}, // разработать на секретном предприятии
rus_verbs:качать{}, // качать на качелях
rus_verbs:тушить{}, // тушить на крыше пожар
rus_verbs:охранять{}, // охранять на территории базы
rus_verbs:приметить{}, // приметить на взгорке
rus_verbs:скрыть{}, // скрыть на теле
rus_verbs:удерживать{}, // удерживать на руке
rus_verbs:усвоить{}, // усвоить на уроке
rus_verbs:растаять{}, // растаять на солнечной стороне
rus_verbs:красоваться{}, // красоваться на виду
rus_verbs:сохраняться{}, // сохраняться на холоде
rus_verbs:лечить{}, // лечить на дому
rus_verbs:прокатиться{}, // прокатиться на уницикле
rus_verbs:договариваться{}, // договариваться на нейтральной территории
rus_verbs:качнуться{}, // качнуться на одной ноге
rus_verbs:опубликовать{}, // опубликовать на сайте
rus_verbs:отражаться{}, // отражаться на поверхности воды
rus_verbs:обедать{}, // обедать на веранде
rus_verbs:посидеть{}, // посидеть на лавочке
rus_verbs:сообщаться{}, // сообщаться на официальном сайте
rus_verbs:свершиться{}, // свершиться на заседании
rus_verbs:ночевать{}, // ночевать на даче
rus_verbs:темнеть{}, // темнеть на свету
rus_verbs:гибнуть{}, // гибнуть на территории полигона
rus_verbs:усиливаться{}, // усиливаться на территории округа
rus_verbs:проживать{}, // проживать на даче
rus_verbs:исследовать{}, // исследовать на большой глубине
rus_verbs:обитать{}, // обитать на громадной глубине
rus_verbs:сталкиваться{}, // сталкиваться на большой высоте
rus_verbs:таиться{}, // таиться на большой глубине
rus_verbs:спасать{}, // спасать на пожаре
rus_verbs:сказываться{}, // сказываться на общем результате
rus_verbs:заблудиться{}, // заблудиться на стройке
rus_verbs:пошарить{}, // пошарить на полках
rus_verbs:планировать{}, // планировать на бумаге
rus_verbs:ранить{}, // ранить на полигоне
rus_verbs:хлопать{}, // хлопать на сцене
rus_verbs:основать{}, // основать на горе новый монастырь
rus_verbs:отбить{}, // отбить на столе
rus_verbs:отрицать{}, // отрицать на заседании комиссии
rus_verbs:устоять{}, // устоять на ногах
rus_verbs:отзываться{}, // отзываться на страницах отчёта
rus_verbs:притормозить{}, // притормозить на обочине
rus_verbs:читаться{}, // читаться на лице
rus_verbs:заиграть{}, // заиграть на саксофоне
rus_verbs:зависнуть{}, // зависнуть на игровой площадке
rus_verbs:сознаться{}, // сознаться на допросе
rus_verbs:выясняться{}, // выясняться на очной ставке
rus_verbs:наводить{}, // наводить на столе порядок
rus_verbs:покоиться{}, // покоиться на кладбище
rus_verbs:значиться{}, // значиться на бейджике
rus_verbs:съехать{}, // съехать на санках
rus_verbs:познакомить{}, // познакомить на свадьбе
rus_verbs:завязать{}, // завязать на спине
rus_verbs:грохнуть{}, // грохнуть на площади
rus_verbs:разъехаться{}, // разъехаться на узкой дороге
rus_verbs:столпиться{}, // столпиться на крыльце
rus_verbs:порыться{}, // порыться на полках
rus_verbs:ослабить{}, // ослабить на шее
rus_verbs:оправдывать{}, // оправдывать на суде
rus_verbs:обнаруживаться{}, // обнаруживаться на складе
rus_verbs:спастись{}, // спастись на дереве
rus_verbs:прерваться{}, // прерваться на полуслове
rus_verbs:строиться{}, // строиться на пустыре
rus_verbs:познать{}, // познать на практике
rus_verbs:путешествовать{}, // путешествовать на поезде
rus_verbs:побеждать{}, // побеждать на ринге
rus_verbs:рассматриваться{}, // рассматриваться на заседании
rus_verbs:продаваться{}, // продаваться на открытом рынке
rus_verbs:разместиться{}, // разместиться на базе
rus_verbs:завыть{}, // завыть на холме
rus_verbs:настигнуть{}, // настигнуть на окраине
rus_verbs:укрыться{}, // укрыться на чердаке
rus_verbs:расплакаться{}, // расплакаться на заседании комиссии
rus_verbs:заканчивать{}, // заканчивать на последнем задании
rus_verbs:пролежать{}, // пролежать на столе
rus_verbs:громоздиться{}, // громоздиться на полу
rus_verbs:замерзнуть{}, // замерзнуть на открытом воздухе
rus_verbs:поскользнуться{}, // поскользнуться на льду
rus_verbs:таскать{}, // таскать на спине
rus_verbs:просматривать{}, // просматривать на сайте
rus_verbs:обдумать{}, // обдумать на досуге
rus_verbs:гадать{}, // гадать на кофейной гуще
rus_verbs:останавливать{}, // останавливать на выходе
rus_verbs:обозначать{}, // обозначать на странице
rus_verbs:долететь{}, // долететь на спортивном байке
rus_verbs:тесниться{}, // тесниться на чердачке
rus_verbs:хоронить{}, // хоронить на частном кладбище
rus_verbs:установиться{}, // установиться на юге
rus_verbs:прикидывать{}, // прикидывать на клочке бумаги
rus_verbs:затаиться{}, // затаиться на дереве
rus_verbs:раздобыть{}, // раздобыть на складе
rus_verbs:перебросить{}, // перебросить на вертолетах
rus_verbs:захватывать{}, // захватывать на базе
rus_verbs:сказаться{}, // сказаться на итоговых оценках
rus_verbs:покачиваться{}, // покачиваться на волнах
rus_verbs:крутиться{}, // крутиться на кухне
rus_verbs:помещаться{}, // помещаться на полке
rus_verbs:питаться{}, // питаться на помойке
rus_verbs:отдохнуть{}, // отдохнуть на загородной вилле
rus_verbs:кататься{}, // кататься на велике
rus_verbs:поработать{}, // поработать на стройке
rus_verbs:ограбить{}, // ограбить на пустыре
rus_verbs:зарабатывать{}, // зарабатывать на бирже
rus_verbs:преуспеть{}, // преуспеть на ниве искусства
rus_verbs:заерзать{}, // заерзать на стуле
rus_verbs:разъяснить{}, // разъяснить на полях
rus_verbs:отчеканить{}, // отчеканить на медной пластине
rus_verbs:торговать{}, // торговать на рынке
rus_verbs:поколебаться{}, // поколебаться на пороге
rus_verbs:прикинуть{}, // прикинуть на бумажке
rus_verbs:рассечь{}, // рассечь на тупом конце
rus_verbs:посмеяться{}, // посмеяться на переменке
rus_verbs:остыть{}, // остыть на морозном воздухе
rus_verbs:запереться{}, // запереться на чердаке
rus_verbs:обогнать{}, // обогнать на повороте
rus_verbs:подтянуться{}, // подтянуться на турнике
rus_verbs:привозить{}, // привозить на машине
rus_verbs:подбирать{}, // подбирать на полу
rus_verbs:уничтожать{}, // уничтожать на подходе
rus_verbs:притаиться{}, // притаиться на вершине
rus_verbs:плясать{}, // плясать на костях
rus_verbs:поджидать{}, // поджидать на вокзале
rus_verbs:закончить{}, // Мы закончили игру на самом интересном месте (САМ не может быть первым прилагательным в цепочке!)
rus_verbs:смениться{}, // смениться на посту
rus_verbs:посчитать{}, // посчитать на пальцах
rus_verbs:прицелиться{}, // прицелиться на бегу
rus_verbs:нарисовать{}, // нарисовать на стене
rus_verbs:прыгать{}, // прыгать на сцене
rus_verbs:повертеть{}, // повертеть на пальце
rus_verbs:попрощаться{}, // попрощаться на панихиде
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на диване
rus_verbs:разобрать{}, // разобрать на столе
rus_verbs:помереть{}, // помереть на чужбине
rus_verbs:различить{}, // различить на нечеткой фотографии
rus_verbs:рисовать{}, // рисовать на доске
rus_verbs:проследить{}, // проследить на экране
rus_verbs:задремать{}, // задремать на диване
rus_verbs:ругаться{}, // ругаться на людях
rus_verbs:сгореть{}, // сгореть на работе
rus_verbs:зазвучать{}, // зазвучать на коротких волнах
rus_verbs:задохнуться{}, // задохнуться на вершине горы
rus_verbs:порождать{}, // порождать на поверхности небольшую рябь
rus_verbs:отдыхать{}, // отдыхать на курорте
rus_verbs:образовать{}, // образовать на дне толстый слой
rus_verbs:поправиться{}, // поправиться на дармовых харчах
rus_verbs:отмечать{}, // отмечать на календаре
rus_verbs:реять{}, // реять на флагштоке
rus_verbs:ползти{}, // ползти на коленях
rus_verbs:продавать{}, // продавать на аукционе
rus_verbs:сосредоточиться{}, // сосредоточиться на основной задаче
rus_verbs:рыскать{}, // мышки рыскали на кухне
rus_verbs:расстегнуть{}, // расстегнуть на куртке все пуговицы
rus_verbs:напасть{}, // напасть на территории другого государства
rus_verbs:издать{}, // издать на западе
rus_verbs:оставаться{}, // оставаться на страже порядка
rus_verbs:появиться{}, // наконец появиться на экране
rus_verbs:лежать{}, // лежать на столе
rus_verbs:ждать{}, // ждать на берегу
инфинитив:писать{aux stress="пис^ать"}, // писать на бумаге
глагол:писать{aux stress="пис^ать"},
rus_verbs:оказываться{}, // оказываться на полу
rus_verbs:поставить{}, // поставить на столе
rus_verbs:держать{}, // держать на крючке
rus_verbs:выходить{}, // выходить на остановке
rus_verbs:заговорить{}, // заговорить на китайском языке
rus_verbs:ожидать{}, // ожидать на стоянке
rus_verbs:закричать{}, // закричал на минарете муэдзин
rus_verbs:простоять{}, // простоять на посту
rus_verbs:продолжить{}, // продолжить на первом этаже
rus_verbs:ощутить{}, // ощутить на себе влияние кризиса
rus_verbs:состоять{}, // состоять на учете
rus_verbs:готовиться{},
инфинитив:акклиматизироваться{вид:несоверш}, // альпинисты готовятся акклиматизироваться на новой высоте
глагол:акклиматизироваться{вид:несоверш},
rus_verbs:арестовать{}, // грабители были арестованы на месте преступления
rus_verbs:схватить{}, // грабители были схвачены на месте преступления
инфинитив:атаковать{ вид:соверш }, // взвод был атакован на границе
глагол:атаковать{ вид:соверш },
прилагательное:атакованный{ вид:соверш },
прилагательное:атаковавший{ вид:соверш },
rus_verbs:базировать{}, // установка будет базирована на границе
rus_verbs:базироваться{}, // установка базируется на границе
rus_verbs:барахтаться{}, // дети барахтались на мелководье
rus_verbs:браконьерить{}, // Охотники браконьерили ночью на реке
rus_verbs:браконьерствовать{}, // Охотники ночью браконьерствовали на реке
rus_verbs:бренчать{}, // парень что-то бренчал на гитаре
rus_verbs:бренькать{}, // парень что-то бренькает на гитаре
rus_verbs:начать{}, // Рынок акций РФ начал торги на отрицательной территории.
rus_verbs:буксовать{}, // Колеса буксуют на льду
rus_verbs:вертеться{}, // Непоседливый ученик много вертится на стуле
rus_verbs:взвести{}, // Боец взвел на оружии предохранитель
rus_verbs:вилять{}, // Машина сильно виляла на дороге
rus_verbs:висеть{}, // Яблоко висит на ветке
rus_verbs:возлежать{}, // возлежать на лежанке
rus_verbs:подниматься{}, // Мы поднимаемся на лифте
rus_verbs:подняться{}, // Мы поднимемся на лифте
rus_verbs:восседать{}, // Коля восседает на лошади
rus_verbs:воссиять{}, // Луна воссияла на небе
rus_verbs:воцариться{}, // Мир воцарился на всей земле
rus_verbs:воцаряться{}, // Мир воцаряется на всей земле
rus_verbs:вращать{}, // вращать на поясе
rus_verbs:вращаться{}, // вращаться на поясе
rus_verbs:встретить{}, // встретить друга на улице
rus_verbs:встретиться{}, // встретиться на занятиях
rus_verbs:встречать{}, // встречать на занятиях
rus_verbs:въебывать{}, // въебывать на работе
rus_verbs:въезжать{}, // въезжать на автомобиле
rus_verbs:въехать{}, // въехать на автомобиле
rus_verbs:выгорать{}, // ткань выгорает на солнце
rus_verbs:выгореть{}, // ткань выгорела на солнце
rus_verbs:выгравировать{}, // выгравировать на табличке надпись
rus_verbs:выжить{}, // выжить на необитаемом острове
rus_verbs:вылежаться{}, // помидоры вылежались на солнце
rus_verbs:вылеживаться{}, // вылеживаться на солнце
rus_verbs:выместить{}, // выместить на ком-то злобу
rus_verbs:вымещать{}, // вымещать на ком-то свое раздражение
rus_verbs:вымещаться{}, // вымещаться на ком-то
rus_verbs:выращивать{}, // выращивать на грядке помидоры
rus_verbs:выращиваться{}, // выращиваться на грядке
инфинитив:вырезать{вид:соверш}, // вырезать на доске надпись
глагол:вырезать{вид:соверш},
инфинитив:вырезать{вид:несоверш},
глагол:вырезать{вид:несоверш},
rus_verbs:вырисоваться{}, // вырисоваться на графике
rus_verbs:вырисовываться{}, // вырисовываться на графике
rus_verbs:высаживать{}, // высаживать на необитаемом острове
rus_verbs:высаживаться{}, // высаживаться на острове
rus_verbs:высвечивать{}, // высвечивать на дисплее температуру
rus_verbs:высвечиваться{}, // высвечиваться на дисплее
rus_verbs:выстроить{}, // выстроить на фундаменте
rus_verbs:выстроиться{}, // выстроиться на плацу
rus_verbs:выстудить{}, // выстудить на морозе
rus_verbs:выстудиться{}, // выстудиться на морозе
rus_verbs:выстужать{}, // выстужать на морозе
rus_verbs:выстуживать{}, // выстуживать на морозе
rus_verbs:выстуживаться{}, // выстуживаться на морозе
rus_verbs:выстукать{}, // выстукать на клавиатуре
rus_verbs:выстукивать{}, // выстукивать на клавиатуре
rus_verbs:выстукиваться{}, // выстукиваться на клавиатуре
rus_verbs:выступать{}, // выступать на сцене
rus_verbs:выступить{}, // выступить на сцене
rus_verbs:выстучать{}, // выстучать на клавиатуре
rus_verbs:выстывать{}, // выстывать на морозе
rus_verbs:выстыть{}, // выстыть на морозе
rus_verbs:вытатуировать{}, // вытатуировать на руке якорь
rus_verbs:говорить{}, // говорить на повышенных тонах
rus_verbs:заметить{}, // заметить на берегу
rus_verbs:стоять{}, // твёрдо стоять на ногах
rus_verbs:оказаться{}, // оказаться на передовой линии
rus_verbs:почувствовать{}, // почувствовать на своей шкуре
rus_verbs:остановиться{}, // остановиться на первом пункте
rus_verbs:показаться{}, // показаться на горизонте
rus_verbs:чувствовать{}, // чувствовать на своей шкуре
rus_verbs:искать{}, // искать на открытом пространстве
rus_verbs:иметься{}, // иметься на складе
rus_verbs:клясться{}, // клясться на Коране
rus_verbs:прервать{}, // прервать на полуслове
rus_verbs:играть{}, // играть на чувствах
rus_verbs:спуститься{}, // спуститься на парашюте
rus_verbs:понадобиться{}, // понадобиться на экзамене
rus_verbs:служить{}, // служить на флоте
rus_verbs:подобрать{}, // подобрать на улице
rus_verbs:появляться{}, // появляться на сцене
rus_verbs:селить{}, // селить на чердаке
rus_verbs:поймать{}, // поймать на границе
rus_verbs:увидать{}, // увидать на опушке
rus_verbs:подождать{}, // подождать на перроне
rus_verbs:прочесть{}, // прочесть на полях
rus_verbs:тонуть{}, // тонуть на мелководье
rus_verbs:ощущать{}, // ощущать на коже
rus_verbs:отметить{}, // отметить на полях
rus_verbs:показывать{}, // показывать на графике
rus_verbs:разговаривать{}, // разговаривать на иностранном языке
rus_verbs:прочитать{}, // прочитать на сайте
rus_verbs:попробовать{}, // попробовать на практике
rus_verbs:замечать{}, // замечать на коже грязь
rus_verbs:нести{}, // нести на плечах
rus_verbs:носить{}, // носить на голове
rus_verbs:гореть{}, // гореть на работе
rus_verbs:застыть{}, // застыть на пороге
инфинитив:жениться{ вид:соверш }, // жениться на королеве
глагол:жениться{ вид:соверш },
прилагательное:женатый{},
прилагательное:женившийся{},
rus_verbs:спрятать{}, // спрятать на чердаке
rus_verbs:развернуться{}, // развернуться на плацу
rus_verbs:строить{}, // строить на песке
rus_verbs:устроить{}, // устроить на даче тестральный вечер
rus_verbs:настаивать{}, // настаивать на выполнении приказа
rus_verbs:находить{}, // находить на берегу
rus_verbs:мелькнуть{}, // мелькнуть на экране
rus_verbs:очутиться{}, // очутиться на опушке леса
инфинитив:использовать{вид:соверш}, // использовать на работе
глагол:использовать{вид:соверш},
инфинитив:использовать{вид:несоверш},
глагол:использовать{вид:несоверш},
прилагательное:использованный{},
прилагательное:использующий{},
прилагательное:использовавший{},
rus_verbs:лететь{}, // лететь на воздушном шаре
rus_verbs:смеяться{}, // смеяться на сцене
rus_verbs:ездить{}, // ездить на мопеде
rus_verbs:заснуть{}, // заснуть на диване
rus_verbs:застать{}, // застать на рабочем месте
rus_verbs:очнуться{}, // очнуться на больничной койке
rus_verbs:разглядеть{}, // разглядеть на фотографии
rus_verbs:обойти{}, // обойти на вираже
rus_verbs:удержаться{}, // удержаться на троне
rus_verbs:побывать{}, // побывать на другой планете
rus_verbs:заняться{}, // заняться на выходных делом
rus_verbs:вянуть{}, // вянуть на солнце
rus_verbs:постоять{}, // постоять на голове
rus_verbs:приобрести{}, // приобрести на распродаже
rus_verbs:попасться{}, // попасться на краже
rus_verbs:продолжаться{}, // продолжаться на земле
rus_verbs:открывать{}, // открывать на арене
rus_verbs:создавать{}, // создавать на сцене
rus_verbs:обсуждать{}, // обсуждать на кухне
rus_verbs:отыскать{}, // отыскать на полу
rus_verbs:уснуть{}, // уснуть на диване
rus_verbs:задержаться{}, // задержаться на работе
rus_verbs:курить{}, // курить на свежем воздухе
rus_verbs:приподняться{}, // приподняться на локтях
rus_verbs:установить{}, // установить на вершине
rus_verbs:запереть{}, // запереть на балконе
rus_verbs:синеть{}, // синеть на воздухе
rus_verbs:убивать{}, // убивать на нейтральной территории
rus_verbs:скрываться{}, // скрываться на даче
rus_verbs:родить{}, // родить на полу
rus_verbs:описать{}, // описать на страницах книги
rus_verbs:перехватить{}, // перехватить на подлете
rus_verbs:скрывать{}, // скрывать на даче
rus_verbs:сменить{}, // сменить на посту
rus_verbs:мелькать{}, // мелькать на экране
rus_verbs:присутствовать{}, // присутствовать на мероприятии
rus_verbs:украсть{}, // украсть на рынке
rus_verbs:победить{}, // победить на ринге
rus_verbs:упомянуть{}, // упомянуть на страницах романа
rus_verbs:плыть{}, // плыть на старой лодке
rus_verbs:повиснуть{}, // повиснуть на перекладине
rus_verbs:нащупать{}, // нащупать на дне
rus_verbs:затихнуть{}, // затихнуть на дне
rus_verbs:построить{}, // построить на участке
rus_verbs:поддерживать{}, // поддерживать на поверхности
rus_verbs:заработать{}, // заработать на бирже
rus_verbs:провалиться{}, // провалиться на экзамене
rus_verbs:сохранить{}, // сохранить на диске
rus_verbs:располагаться{}, // располагаться на софе
rus_verbs:поклясться{}, // поклясться на библии
rus_verbs:сражаться{}, // сражаться на арене
rus_verbs:спускаться{}, // спускаться на дельтаплане
rus_verbs:уничтожить{}, // уничтожить на подступах
rus_verbs:изучить{}, // изучить на практике
rus_verbs:рождаться{}, // рождаться на праздниках
rus_verbs:прилететь{}, // прилететь на самолете
rus_verbs:догнать{}, // догнать на перекрестке
rus_verbs:изобразить{}, // изобразить на бумаге
rus_verbs:проехать{}, // проехать на тракторе
rus_verbs:приготовить{}, // приготовить на масле
rus_verbs:споткнуться{}, // споткнуться на полу
rus_verbs:собирать{}, // собирать на берегу
rus_verbs:отсутствовать{}, // отсутствовать на тусовке
rus_verbs:приземлиться{}, // приземлиться на военном аэродроме
rus_verbs:сыграть{}, // сыграть на трубе
rus_verbs:прятаться{}, // прятаться на даче
rus_verbs:спрятаться{}, // спрятаться на чердаке
rus_verbs:провозгласить{}, // провозгласить на митинге
rus_verbs:изложить{}, // изложить на бумаге
rus_verbs:использоваться{}, // использоваться на практике
rus_verbs:замяться{}, // замяться на входе
rus_verbs:раздаваться{}, // Крик ягуара раздается на краю болота
rus_verbs:сверкнуть{}, // сверкнуть на солнце
rus_verbs:сверкать{}, // сверкать на свету
rus_verbs:задержать{}, // задержать на митинге
rus_verbs:осечься{}, // осечься на первом слове
rus_verbs:хранить{}, // хранить на банковском счету
rus_verbs:шутить{}, // шутить на уроке
rus_verbs:кружиться{}, // кружиться на балу
rus_verbs:чертить{}, // чертить на доске
rus_verbs:отразиться{}, // отразиться на оценках
rus_verbs:греть{}, // греть на солнце
rus_verbs:рассуждать{}, // рассуждать на страницах своей книги
rus_verbs:окружать{}, // окружать на острове
rus_verbs:сопровождать{}, // сопровождать на охоте
rus_verbs:заканчиваться{}, // заканчиваться на самом интересном месте
rus_verbs:содержаться{}, // содержаться на приусадебном участке
rus_verbs:поселиться{}, // поселиться на даче
rus_verbs:запеть{}, // запеть на сцене
инфинитив:провозить{ вид:несоверш }, // провозить на теле
глагол:провозить{ вид:несоверш },
прилагательное:провезенный{},
прилагательное:провозивший{вид:несоверш},
прилагательное:провозящий{вид:несоверш},
деепричастие:провозя{},
rus_verbs:мочить{}, // мочить на месте
rus_verbs:преследовать{}, // преследовать на территории другого штата
rus_verbs:пролететь{}, // пролетел на параплане
rus_verbs:драться{}, // драться на рапирах
rus_verbs:просидеть{}, // просидеть на занятиях
rus_verbs:убираться{}, // убираться на балконе
rus_verbs:таять{}, // таять на солнце
rus_verbs:проверять{}, // проверять на полиграфе
rus_verbs:убеждать{}, // убеждать на примере
rus_verbs:скользить{}, // скользить на льду
rus_verbs:приобретать{}, // приобретать на распродаже
rus_verbs:летать{}, // летать на метле
rus_verbs:толпиться{}, // толпиться на перроне
rus_verbs:плавать{}, // плавать на надувном матрасе
rus_verbs:описывать{}, // описывать на страницах повести
rus_verbs:пробыть{}, // пробыть на солнце слишком долго
rus_verbs:застрять{}, // застрять на верхнем этаже
rus_verbs:метаться{}, // метаться на полу
rus_verbs:сжечь{}, // сжечь на костре
rus_verbs:расслабиться{}, // расслабиться на кушетке
rus_verbs:услыхать{}, // услыхать на рынке
rus_verbs:удержать{}, // удержать на прежнем уровне
rus_verbs:образоваться{}, // образоваться на дне
rus_verbs:рассмотреть{}, // рассмотреть на поверхности чипа
rus_verbs:уезжать{}, // уезжать на попутке
rus_verbs:похоронить{}, // похоронить на закрытом кладбище
rus_verbs:настоять{}, // настоять на пересмотре оценок
rus_verbs:растянуться{}, // растянуться на горячем песке
rus_verbs:покрутить{}, // покрутить на шесте
rus_verbs:обнаружиться{}, // обнаружиться на болоте
rus_verbs:гулять{}, // гулять на свадьбе
rus_verbs:утонуть{}, // утонуть на курорте
rus_verbs:храниться{}, // храниться на депозите
rus_verbs:танцевать{}, // танцевать на свадьбе
rus_verbs:трудиться{}, // трудиться на заводе
инфинитив:засыпать{переходность:непереходный вид:несоверш}, // засыпать на кровати
глагол:засыпать{переходность:непереходный вид:несоверш},
деепричастие:засыпая{переходность:непереходный вид:несоверш},
прилагательное:засыпавший{переходность:непереходный вид:несоверш},
прилагательное:засыпающий{ вид:несоверш переходность:непереходный }, // ребенок, засыпающий на руках
rus_verbs:сушить{}, // сушить на открытом воздухе
rus_verbs:зашевелиться{}, // зашевелиться на чердаке
rus_verbs:обдумывать{}, // обдумывать на досуге
rus_verbs:докладывать{}, // докладывать на научной конференции
rus_verbs:промелькнуть{}, // промелькнуть на экране
// прилагательное:находящийся{ вид:несоверш }, // колонна, находящаяся на ничейной территории
прилагательное:написанный{}, // слово, написанное на заборе
rus_verbs:умещаться{}, // компьютер, умещающийся на ладони
rus_verbs:открыть{}, // книга, открытая на последней странице
rus_verbs:спать{}, // йог, спящий на гвоздях
rus_verbs:пробуксовывать{}, // колесо, пробуксовывающее на обледенелом асфальте
rus_verbs:забуксовать{}, // колесо, забуксовавшее на обледенелом асфальте
rus_verbs:отобразиться{}, // удивление, отобразившееся на лице
rus_verbs:увидеть{}, // на полу я увидел чьи-то следы
rus_verbs:видеть{}, // на полу я вижу чьи-то следы
rus_verbs:оставить{}, // Мел оставил на доске белый след.
rus_verbs:оставлять{}, // Мел оставляет на доске белый след.
rus_verbs:встречаться{}, // встречаться на лекциях
rus_verbs:познакомиться{}, // познакомиться на занятиях
rus_verbs:устроиться{}, // она устроилась на кровати
rus_verbs:ложиться{}, // ложись на полу
rus_verbs:останавливаться{}, // останавливаться на достигнутом
rus_verbs:спотыкаться{}, // спотыкаться на ровном месте
rus_verbs:распечатать{}, // распечатать на бумаге
rus_verbs:распечатывать{}, // распечатывать на бумаге
rus_verbs:просмотреть{}, // просмотреть на бумаге
rus_verbs:закрепляться{}, // закрепляться на плацдарме
rus_verbs:погреться{}, // погреться на солнышке
rus_verbs:мешать{}, // Он мешал краски на палитре.
rus_verbs:занять{}, // Он занял первое место на соревнованиях.
rus_verbs:заговариваться{}, // Он заговаривался иногда на уроках.
деепричастие:женившись{ вид:соверш },
rus_verbs:везти{}, // Он везёт песок на тачке.
прилагательное:казненный{}, // Он был казнён на электрическом стуле.
rus_verbs:прожить{}, // Он безвыездно прожил всё лето на даче.
rus_verbs:принести{}, // Официантка принесла нам обед на подносе.
rus_verbs:переписать{}, // Перепишите эту рукопись на машинке.
rus_verbs:идти{}, // Поезд идёт на малой скорости.
rus_verbs:петь{}, // птички поют на рассвете
rus_verbs:смотреть{}, // Смотри на обороте.
rus_verbs:прибрать{}, // прибрать на столе
rus_verbs:прибраться{}, // прибраться на столе
rus_verbs:растить{}, // растить капусту на огороде
rus_verbs:тащить{}, // тащить ребенка на руках
rus_verbs:убирать{}, // убирать на столе
rus_verbs:простыть{}, // Я простыл на морозе.
rus_verbs:сиять{}, // ясные звезды мирно сияли на безоблачном весеннем небе.
rus_verbs:проводиться{}, // такие эксперименты не проводятся на воде
rus_verbs:достать{}, // Я не могу достать до яблок на верхних ветках.
rus_verbs:расплыться{}, // Чернила расплылись на плохой бумаге.
rus_verbs:вскочить{}, // У него вскочил прыщ на носу.
rus_verbs:свить{}, // У нас на балконе воробей свил гнездо.
rus_verbs:оторваться{}, // У меня на пальто оторвалась пуговица.
rus_verbs:восходить{}, // Солнце восходит на востоке.
rus_verbs:блестеть{}, // Снег блестит на солнце.
rus_verbs:побить{}, // Рысак побил всех лошадей на скачках.
rus_verbs:литься{}, // Реки крови льются на войне.
rus_verbs:держаться{}, // Ребёнок уже твёрдо держится на ногах.
rus_verbs:клубиться{}, // Пыль клубится на дороге.
инфинитив:написать{ aux stress="напис^ать" }, // Ты должен написать статью на английском языке
глагол:написать{ aux stress="напис^ать" }, // Он написал статью на русском языке.
// глагол:находиться{вид:несоверш}, // мой поезд находится на первом пути
// инфинитив:находиться{вид:несоверш},
rus_verbs:жить{}, // Было интересно жить на курорте.
rus_verbs:повидать{}, // Он много повидал на своём веку.
rus_verbs:разъезжаться{}, // Ноги разъезжаются не только на льду.
rus_verbs:расположиться{}, // Оба села расположились на берегу реки.
rus_verbs:объясняться{}, // Они объясняются на иностранном языке.
rus_verbs:прощаться{}, // Они долго прощались на вокзале.
rus_verbs:работать{}, // Она работает на ткацкой фабрике.
rus_verbs:купить{}, // Она купила молоко на рынке.
rus_verbs:поместиться{}, // Все книги поместились на полке.
глагол:проводить{вид:несоверш}, инфинитив:проводить{вид:несоверш}, // Нужно проводить теорию на практике.
rus_verbs:пожить{}, // Недолго она пожила на свете.
rus_verbs:краснеть{}, // Небо краснеет на закате.
rus_verbs:бывать{}, // На Волге бывает сильное волнение.
rus_verbs:ехать{}, // Мы туда ехали на автобусе.
rus_verbs:провести{}, // Мы провели месяц на даче.
rus_verbs:поздороваться{}, // Мы поздоровались при встрече на улице.
rus_verbs:расти{}, // Арбузы растут теперь не только на юге.
ГЛ_ИНФ(сидеть), // три больших пса сидят на траве
ГЛ_ИНФ(сесть), // три больших пса сели на траву
ГЛ_ИНФ(перевернуться), // На дороге перевернулся автомобиль
ГЛ_ИНФ(повезти), // я повезу тебя на машине
ГЛ_ИНФ(отвезти), // мы отвезем тебя на такси
ГЛ_ИНФ(пить), // пить на кухне чай
ГЛ_ИНФ(найти), // найти на острове
ГЛ_ИНФ(быть), // на этих костях есть следы зубов
ГЛ_ИНФ(высадиться), // помощники высадились на острове
ГЛ_ИНФ(делать),прилагательное:делающий{}, прилагательное:делавший{}, деепричастие:делая{}, // смотрю фильм о том, что пираты делали на необитаемом острове
ГЛ_ИНФ(случиться), // это случилось на опушке леса
ГЛ_ИНФ(продать),
ГЛ_ИНФ(есть) // кошки ели мой корм на песчаном берегу
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: смотреть на youtube
fact гл_предл
{
if context { Гл_НА_Предл предлог:в{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:предл} }
then return true
}
// локатив
fact гл_предл
{
if context { Гл_НА_Предл предлог:на{} *:*{падеж:мест} }
then return true
}
#endregion ПРЕДЛОЖНЫЙ
#region ВИНИТЕЛЬНЫЙ
// НА+винительный падеж:
// ЗАБИРАТЬСЯ НА ВЕРШИНУ ГОРЫ
#region VerbList
wordentry_set Гл_НА_Вин=
{
rus_verbs:переметнуться{}, // Ее взгляд растерянно переметнулся на Лили.
rus_verbs:отогнать{}, // Водитель отогнал машину на стоянку.
rus_verbs:фапать{}, // Не фапай на желтяк и не перебивай.
rus_verbs:умножить{}, // Умножьте это количество примерно на 10.
//rus_verbs:умножать{},
rus_verbs:откатить{}, // Откатил Шпак валун на шлях и перекрыл им дорогу.
rus_verbs:откатывать{},
rus_verbs:доносить{}, // Вот и побежали на вас доносить.
rus_verbs:донести{},
rus_verbs:разбирать{}, // Ворованные автомобили злоумышленники разбирали на запчасти и продавали.
безлич_глагол:хватит{}, // - На одну атаку хватит.
rus_verbs:скупиться{}, // Он сражался за жизнь, не скупясь на хитрости и усилия, и пока этот стиль давал неплохие результаты.
rus_verbs:поскупиться{}, // Не поскупись на похвалы!
rus_verbs:подыматься{},
rus_verbs:транспортироваться{},
rus_verbs:бахнуть{}, // Бахнуть стакан на пол
rus_verbs:РАЗДЕЛИТЬ{}, // Президентские выборы разделили Венесуэлу на два непримиримых лагеря (РАЗДЕЛИТЬ)
rus_verbs:НАЦЕЛИВАТЬСЯ{}, // Невдалеке пролетел кондор, нацеливаясь на бизонью тушу. (НАЦЕЛИВАТЬСЯ)
rus_verbs:ВЫПЛЕСНУТЬ{}, // Низкий вибрирующий гул напоминал вулкан, вот-вот готовый выплеснуть на земную твердь потоки раскаленной лавы. (ВЫПЛЕСНУТЬ)
rus_verbs:ИСЧЕЗНУТЬ{}, // Оно фыркнуло и исчезло в лесу на другой стороне дороги (ИСЧЕЗНУТЬ)
rus_verbs:ВЫЗВАТЬ{}, // вызвать своего брата на поединок. (ВЫЗВАТЬ)
rus_verbs:ПОБРЫЗГАТЬ{}, // Матрос побрызгал немного фимиама на крошечный огонь (ПОБРЫЗГАТЬ/БРЫЗГАТЬ/БРЫЗНУТЬ/КАПНУТЬ/КАПАТЬ/ПОКАПАТЬ)
rus_verbs:БРЫЗГАТЬ{},
rus_verbs:БРЫЗНУТЬ{},
rus_verbs:КАПНУТЬ{},
rus_verbs:КАПАТЬ{},
rus_verbs:ПОКАПАТЬ{},
rus_verbs:ПООХОТИТЬСЯ{}, // Мы можем когда-нибудь вернуться и поохотиться на него. (ПООХОТИТЬСЯ/ОХОТИТЬСЯ)
rus_verbs:ОХОТИТЬСЯ{}, //
rus_verbs:ПОПАСТЬСЯ{}, // Не думал я, что они попадутся на это (ПОПАСТЬСЯ/НАРВАТЬСЯ/НАТОЛКНУТЬСЯ)
rus_verbs:НАРВАТЬСЯ{}, //
rus_verbs:НАТОЛКНУТЬСЯ{}, //
rus_verbs:ВЫСЛАТЬ{}, // Он выслал разведчиков на большое расстояние от основного отряда. (ВЫСЛАТЬ)
прилагательное:ПОХОЖИЙ{}, // Ты не выглядишь похожим на индейца (ПОХОЖИЙ)
rus_verbs:РАЗОРВАТЬ{}, // Через минуту он был мертв и разорван на части. (РАЗОРВАТЬ)
rus_verbs:СТОЛКНУТЬ{}, // Только быстрыми выпадами копья он сумел столкнуть их обратно на карниз. (СТОЛКНУТЬ/СТАЛКИВАТЬ)
rus_verbs:СТАЛКИВАТЬ{}, //
rus_verbs:СПУСТИТЬ{}, // Я побежал к ним, но они к тому времени спустили лодку на воду (СПУСТИТЬ)
rus_verbs:ПЕРЕБРАСЫВАТЬ{}, // Сирия перебрасывает на юг страны воинские подкрепления (ПЕРЕБРАСЫВАТЬ, ПЕРЕБРОСИТЬ, НАБРАСЫВАТЬ, НАБРОСИТЬ)
rus_verbs:ПЕРЕБРОСИТЬ{}, //
rus_verbs:НАБРАСЫВАТЬ{}, //
rus_verbs:НАБРОСИТЬ{}, //
rus_verbs:СВЕРНУТЬ{}, // Он вывел машину на бульвар и поехал на восток, а затем свернул на юг. (СВЕРНУТЬ/СВОРАЧИВАТЬ/ПОВЕРНУТЬ/ПОВОРАЧИВАТЬ)
rus_verbs:СВОРАЧИВАТЬ{}, // //
rus_verbs:ПОВЕРНУТЬ{}, //
rus_verbs:ПОВОРАЧИВАТЬ{}, //
rus_verbs:наорать{},
rus_verbs:ПРОДВИНУТЬСЯ{}, // Полк продвинется на десятки километров (ПРОДВИНУТЬСЯ)
rus_verbs:БРОСАТЬ{}, // Он бросает обещания на ветер (БРОСАТЬ)
rus_verbs:ОДОЛЖИТЬ{}, // Я вам одолжу книгу на десять дней (ОДОЛЖИТЬ)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:перегонять{},
rus_verbs:выгонять{},
rus_verbs:выгнать{},
rus_verbs:СВОДИТЬСЯ{}, // сейчас панели кузовов расходятся по десяткам покрасочных постов и потом сводятся вновь на общий конвейер (СВОДИТЬСЯ)
rus_verbs:ПОЖЕРТВОВАТЬ{}, // Бывший функционер компартии Эстонии пожертвовал деньги на расследования преступлений коммунизма (ПОЖЕРТВОВАТЬ)
rus_verbs:ПРОВЕРЯТЬ{}, // Школьников будут принудительно проверять на курение (ПРОВЕРЯТЬ)
rus_verbs:ОТПУСТИТЬ{}, // Приставы отпустят должников на отдых (ОТПУСТИТЬ)
rus_verbs:использоваться{}, // имеющийся у государства денежный запас активно используется на поддержание рынка акций
rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:наблюдать{}, // Судья , долго наблюдавший в трубу , вдруг вскричал
rus_verbs:ШПИОНИТЬ{}, // Канадского офицера, шпионившего на Россию, приговорили к 20 годам тюрьмы (ШПИОНИТЬ НА вин)
rus_verbs:ЗАПЛАНИРОВАТЬ{}, // все деньги , запланированные на сейсмоукрепление домов на Камчатке (ЗАПЛАНИРОВАТЬ НА)
// rus_verbs:ПОХОДИТЬ{}, // больше походил на обвинительную речь , адресованную руководству республики (ПОХОДИТЬ НА)
rus_verbs:ДЕЙСТВОВАТЬ{}, // выявленный контрабандный канал действовал на постоянной основе (ДЕЙСТВОВАТЬ НА)
rus_verbs:ПЕРЕДАТЬ{}, // после чего должно быть передано на рассмотрение суда (ПЕРЕДАТЬ НА вин)
rus_verbs:НАЗНАЧИТЬСЯ{}, // Зимой на эту должность пытался назначиться народный депутат (НАЗНАЧИТЬСЯ НА)
rus_verbs:РЕШИТЬСЯ{}, // Франция решилась на одностороннее и рискованное военное вмешательство (РЕШИТЬСЯ НА)
rus_verbs:ОРИЕНТИРОВАТЬ{}, // Этот браузер полностью ориентирован на планшеты и сенсорный ввод (ОРИЕНТИРОВАТЬ НА вин)
rus_verbs:ЗАВЕСТИ{}, // на Витьку завели дело (ЗАВЕСТИ НА)
rus_verbs:ОБРУШИТЬСЯ{}, // В Северной Осетии на воинскую часть обрушилась снежная лавина (ОБРУШИТЬСЯ В, НА)
rus_verbs:НАСТРАИВАТЬСЯ{}, // гетеродин, настраивающийся на волну (НАСТРАИВАТЬСЯ НА)
rus_verbs:СУЩЕСТВОВАТЬ{}, // Он существует на средства родителей. (СУЩЕСТВОВАТЬ НА)
прилагательное:способный{}, // Он способен на убийство. (СПОСОБНЫЙ НА)
rus_verbs:посыпаться{}, // на Нину посыпались снежинки
инфинитив:нарезаться{ вид:несоверш }, // Урожай собирают механически или вручную, стебли нарезаются на куски и быстро транспортируются на перерабатывающий завод.
глагол:нарезаться{ вид:несоверш },
rus_verbs:пожаловать{}, // скандально известный певец пожаловал к нам на передачу
rus_verbs:показать{}, // Вадим показал на Колю
rus_verbs:съехаться{}, // Финалисты съехались на свои игры в Лос-Анжелес. (СЪЕХАТЬСЯ НА, В)
rus_verbs:расщепляться{}, // Сахароза же быстро расщепляется в пищеварительном тракте на глюкозу и фруктозу (РАСЩЕПЛЯТЬСЯ В, НА)
rus_verbs:упасть{}, // В Таиланде на автобус с российскими туристами упал башенный кран (УПАСТЬ В, НА)
прилагательное:тугой{}, // Бабушка туга на ухо. (ТУГОЙ НА)
rus_verbs:свисать{}, // Волосы свисают на лоб. (свисать на)
rus_verbs:ЦЕНИТЬСЯ{}, // Всякая рабочая рука ценилась на вес золота. (ЦЕНИТЬСЯ НА)
rus_verbs:ШУМЕТЬ{}, // Вы шумите на весь дом! (ШУМЕТЬ НА)
rus_verbs:протянуться{}, // Дорога протянулась на сотни километров. (протянуться на)
rus_verbs:РАССЧИТАТЬ{}, // Книга рассчитана на массового читателя. (РАССЧИТАТЬ НА)
rus_verbs:СОРИЕНТИРОВАТЬ{}, // мы сориентировали процесс на повышение котировок (СОРИЕНТИРОВАТЬ НА)
rus_verbs:рыкнуть{}, // рыкнуть на остальных членов стаи (рыкнуть на)
rus_verbs:оканчиваться{}, // оканчиваться на звонкую согласную (оканчиваться на)
rus_verbs:выехать{}, // посигналить нарушителю, выехавшему на встречную полосу (выехать на)
rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:крениться{}, // корабль кренился на правый борт (крениться на)
rus_verbs:приходиться{}, // основной налоговый гнет приходится на средний бизнес (приходиться на)
rus_verbs:верить{}, // верить людям на слово (верить на слово)
rus_verbs:выезжать{}, // Завтра вся семья выезжает на новую квартиру.
rus_verbs:записать{}, // Запишите меня на завтрашний приём к доктору.
rus_verbs:пасть{}, // Жребий пал на меня.
rus_verbs:ездить{}, // Вчера мы ездили на оперу.
rus_verbs:влезть{}, // Мальчик влез на дерево.
rus_verbs:выбежать{}, // Мальчик выбежал из комнаты на улицу.
rus_verbs:разбиться{}, // окно разбилось на мелкие осколки
rus_verbs:бежать{}, // я бегу на урок
rus_verbs:сбегаться{}, // сбегаться на происшествие
rus_verbs:присылать{}, // присылать на испытание
rus_verbs:надавить{}, // надавить на педать
rus_verbs:внести{}, // внести законопроект на рассмотрение
rus_verbs:вносить{}, // вносить законопроект на рассмотрение
rus_verbs:поворачиваться{}, // поворачиваться на 180 градусов
rus_verbs:сдвинуть{}, // сдвинуть на несколько сантиметров
rus_verbs:опубликовать{}, // С.Митрохин опубликовал компромат на думских подельников Гудкова
rus_verbs:вырасти{}, // Официальный курс доллара вырос на 26 копеек.
rus_verbs:оглядываться{}, // оглядываться на девушек
rus_verbs:расходиться{}, // расходиться на отдых
rus_verbs:поскакать{}, // поскакать на службу
rus_verbs:прыгать{}, // прыгать на сцену
rus_verbs:приглашать{}, // приглашать на обед
rus_verbs:рваться{}, // Кусок ткани рвется на части
rus_verbs:понестись{}, // понестись на волю
rus_verbs:распространяться{}, // распространяться на всех жителей штата
инфинитив:просыпаться{ вид:соверш }, глагол:просыпаться{ вид:соверш }, // просыпаться на пол
инфинитив:просыпаться{ вид:несоверш }, глагол:просыпаться{ вид:несоверш },
деепричастие:просыпавшись{}, деепричастие:просыпаясь{},
rus_verbs:заехать{}, // заехать на пандус
rus_verbs:разобрать{}, // разобрать на составляющие
rus_verbs:опускаться{}, // опускаться на колени
rus_verbs:переехать{}, // переехать на конспиративную квартиру
rus_verbs:закрывать{}, // закрывать глаза на действия конкурентов
rus_verbs:поместить{}, // поместить на поднос
rus_verbs:отходить{}, // отходить на подготовленные позиции
rus_verbs:сыпаться{}, // сыпаться на плечи
rus_verbs:отвезти{}, // отвезти на занятия
rus_verbs:накинуть{}, // накинуть на плечи
rus_verbs:отлететь{}, // отлететь на пол
rus_verbs:закинуть{}, // закинуть на чердак
rus_verbs:зашипеть{}, // зашипеть на собаку
rus_verbs:прогреметь{}, // прогреметь на всю страну
rus_verbs:повалить{}, // повалить на стол
rus_verbs:опереть{}, // опереть на фундамент
rus_verbs:забросить{}, // забросить на антресоль
rus_verbs:подействовать{}, // подействовать на материал
rus_verbs:разделять{}, // разделять на части
rus_verbs:прикрикнуть{}, // прикрикнуть на детей
rus_verbs:разложить{}, // разложить на множители
rus_verbs:провожать{}, // провожать на работу
rus_verbs:катить{}, // катить на стройку
rus_verbs:наложить{}, // наложить запрет на проведение операций с недвижимостью
rus_verbs:сохранять{}, // сохранять на память
rus_verbs:злиться{}, // злиться на друга
rus_verbs:оборачиваться{}, // оборачиваться на свист
rus_verbs:сползти{}, // сползти на землю
rus_verbs:записывать{}, // записывать на ленту
rus_verbs:загнать{}, // загнать на дерево
rus_verbs:забормотать{}, // забормотать на ухо
rus_verbs:протиснуться{}, // протиснуться на самый край
rus_verbs:заторопиться{}, // заторопиться на вручение премии
rus_verbs:гаркнуть{}, // гаркнуть на шалунов
rus_verbs:навалиться{}, // навалиться на виновника всей толпой
rus_verbs:проскользнуть{}, // проскользнуть на крышу дома
rus_verbs:подтянуть{}, // подтянуть на палубу
rus_verbs:скатиться{}, // скатиться на двойки
rus_verbs:давить{}, // давить на жалость
rus_verbs:намекнуть{}, // намекнуть на новые обстоятельства
rus_verbs:замахнуться{}, // замахнуться на святое
rus_verbs:заменить{}, // заменить на свежую салфетку
rus_verbs:свалить{}, // свалить на землю
rus_verbs:стекать{}, // стекать на оголенные провода
rus_verbs:увеличиваться{}, // увеличиваться на сотню процентов
rus_verbs:развалиться{}, // развалиться на части
rus_verbs:сердиться{}, // сердиться на товарища
rus_verbs:обронить{}, // обронить на пол
rus_verbs:подсесть{}, // подсесть на наркоту
rus_verbs:реагировать{}, // реагировать на импульсы
rus_verbs:отпускать{}, // отпускать на волю
rus_verbs:прогнать{}, // прогнать на рабочее место
rus_verbs:ложить{}, // ложить на стол
rus_verbs:рвать{}, // рвать на части
rus_verbs:разлететься{}, // разлететься на кусочки
rus_verbs:превышать{}, // превышать на существенную величину
rus_verbs:сбиться{}, // сбиться на рысь
rus_verbs:пристроиться{}, // пристроиться на хорошую работу
rus_verbs:удрать{}, // удрать на пастбище
rus_verbs:толкать{}, // толкать на преступление
rus_verbs:посматривать{}, // посматривать на экран
rus_verbs:набирать{}, // набирать на судно
rus_verbs:отступать{}, // отступать на дерево
rus_verbs:подуть{}, // подуть на молоко
rus_verbs:плеснуть{}, // плеснуть на голову
rus_verbs:соскользнуть{}, // соскользнуть на землю
rus_verbs:затаить{}, // затаить на кого-то обиду
rus_verbs:обижаться{}, // обижаться на Колю
rus_verbs:смахнуть{}, // смахнуть на пол
rus_verbs:застегнуть{}, // застегнуть на все пуговицы
rus_verbs:спускать{}, // спускать на землю
rus_verbs:греметь{}, // греметь на всю округу
rus_verbs:скосить{}, // скосить на соседа глаз
rus_verbs:отважиться{}, // отважиться на прыжок
rus_verbs:литься{}, // литься на землю
rus_verbs:порвать{}, // порвать на тряпки
rus_verbs:проследовать{}, // проследовать на сцену
rus_verbs:надевать{}, // надевать на голову
rus_verbs:проскочить{}, // проскочить на красный свет
rus_verbs:прилечь{}, // прилечь на диванчик
rus_verbs:разделиться{}, // разделиться на небольшие группы
rus_verbs:завыть{}, // завыть на луну
rus_verbs:переносить{}, // переносить на другую машину
rus_verbs:наговорить{}, // наговорить на сотню рублей
rus_verbs:намекать{}, // намекать на новые обстоятельства
rus_verbs:нападать{}, // нападать на охранников
rus_verbs:убегать{}, // убегать на другое место
rus_verbs:тратить{}, // тратить на развлечения
rus_verbs:присаживаться{}, // присаживаться на корточки
rus_verbs:переместиться{}, // переместиться на вторую линию
rus_verbs:завалиться{}, // завалиться на диван
rus_verbs:удалиться{}, // удалиться на покой
rus_verbs:уменьшаться{}, // уменьшаться на несколько процентов
rus_verbs:обрушить{}, // обрушить на голову
rus_verbs:резать{}, // резать на части
rus_verbs:умчаться{}, // умчаться на юг
rus_verbs:навернуться{}, // навернуться на камень
rus_verbs:примчаться{}, // примчаться на матч
rus_verbs:издавать{}, // издавать на собственные средства
rus_verbs:переключить{}, // переключить на другой язык
rus_verbs:отправлять{}, // отправлять на пенсию
rus_verbs:залечь{}, // залечь на дно
rus_verbs:установиться{}, // установиться на диск
rus_verbs:направлять{}, // направлять на дополнительное обследование
rus_verbs:разрезать{}, // разрезать на части
rus_verbs:оскалиться{}, // оскалиться на прохожего
rus_verbs:рычать{}, // рычать на пьяных
rus_verbs:погружаться{}, // погружаться на дно
rus_verbs:опираться{}, // опираться на костыли
rus_verbs:поторопиться{}, // поторопиться на учебу
rus_verbs:сдвинуться{}, // сдвинуться на сантиметр
rus_verbs:увеличить{}, // увеличить на процент
rus_verbs:опускать{}, // опускать на землю
rus_verbs:созвать{}, // созвать на митинг
rus_verbs:делить{}, // делить на части
rus_verbs:пробиться{}, // пробиться на заключительную часть
rus_verbs:простираться{}, // простираться на много миль
rus_verbs:забить{}, // забить на учебу
rus_verbs:переложить{}, // переложить на чужие плечи
rus_verbs:грохнуться{}, // грохнуться на землю
rus_verbs:прорваться{}, // прорваться на сцену
rus_verbs:разлить{}, // разлить на землю
rus_verbs:укладываться{}, // укладываться на ночевку
rus_verbs:уволить{}, // уволить на пенсию
rus_verbs:наносить{}, // наносить на кожу
rus_verbs:набежать{}, // набежать на берег
rus_verbs:заявиться{}, // заявиться на стрельбище
rus_verbs:налиться{}, // налиться на крышку
rus_verbs:надвигаться{}, // надвигаться на берег
rus_verbs:распустить{}, // распустить на каникулы
rus_verbs:переключиться{}, // переключиться на другую задачу
rus_verbs:чихнуть{}, // чихнуть на окружающих
rus_verbs:шлепнуться{}, // шлепнуться на спину
rus_verbs:устанавливать{}, // устанавливать на крышу
rus_verbs:устанавливаться{}, // устанавливаться на крышу
rus_verbs:устраиваться{}, // устраиваться на работу
rus_verbs:пропускать{}, // пропускать на стадион
инфинитив:сбегать{ вид:соверш }, глагол:сбегать{ вид:соверш }, // сбегать на фильм
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш },
деепричастие:сбегав{}, деепричастие:сбегая{},
rus_verbs:показываться{}, // показываться на глаза
rus_verbs:прибегать{}, // прибегать на урок
rus_verbs:съездить{}, // съездить на ферму
rus_verbs:прославиться{}, // прославиться на всю страну
rus_verbs:опрокинуться{}, // опрокинуться на спину
rus_verbs:насыпать{}, // насыпать на землю
rus_verbs:употреблять{}, // употреблять на корм скоту
rus_verbs:пристроить{}, // пристроить на работу
rus_verbs:заворчать{}, // заворчать на вошедшего
rus_verbs:завязаться{}, // завязаться на поставщиков
rus_verbs:сажать{}, // сажать на стул
rus_verbs:напрашиваться{}, // напрашиваться на жесткие ответные меры
rus_verbs:заменять{}, // заменять на исправную
rus_verbs:нацепить{}, // нацепить на голову
rus_verbs:сыпать{}, // сыпать на землю
rus_verbs:закрываться{}, // закрываться на ремонт
rus_verbs:распространиться{}, // распространиться на всю популяцию
rus_verbs:поменять{}, // поменять на велосипед
rus_verbs:пересесть{}, // пересесть на велосипеды
rus_verbs:подоспеть{}, // подоспеть на разбор
rus_verbs:шипеть{}, // шипеть на собак
rus_verbs:поделить{}, // поделить на части
rus_verbs:подлететь{}, // подлететь на расстояние выстрела
rus_verbs:нажимать{}, // нажимать на все кнопки
rus_verbs:распасться{}, // распасться на части
rus_verbs:приволочь{}, // приволочь на диван
rus_verbs:пожить{}, // пожить на один доллар
rus_verbs:устремляться{}, // устремляться на свободу
rus_verbs:смахивать{}, // смахивать на пол
rus_verbs:забежать{}, // забежать на обед
rus_verbs:увеличиться{}, // увеличиться на существенную величину
rus_verbs:прокрасться{}, // прокрасться на склад
rus_verbs:пущать{}, // пущать на постой
rus_verbs:отклонить{}, // отклонить на несколько градусов
rus_verbs:насмотреться{}, // насмотреться на безобразия
rus_verbs:настроить{}, // настроить на короткие волны
rus_verbs:уменьшиться{}, // уменьшиться на пару сантиметров
rus_verbs:поменяться{}, // поменяться на другую книжку
rus_verbs:расколоться{}, // расколоться на части
rus_verbs:разлиться{}, // разлиться на землю
rus_verbs:срываться{}, // срываться на жену
rus_verbs:осудить{}, // осудить на пожизненное заключение
rus_verbs:передвинуть{}, // передвинуть на первое место
rus_verbs:допускаться{}, // допускаться на полигон
rus_verbs:задвинуть{}, // задвинуть на полку
rus_verbs:повлиять{}, // повлиять на оценку
rus_verbs:отбавлять{}, // отбавлять на осмотр
rus_verbs:сбрасывать{}, // сбрасывать на землю
rus_verbs:накинуться{}, // накинуться на случайных прохожих
rus_verbs:пролить{}, // пролить на кожу руки
rus_verbs:затащить{}, // затащить на сеновал
rus_verbs:перебежать{}, // перебежать на сторону противника
rus_verbs:наливать{}, // наливать на скатерть
rus_verbs:пролезть{}, // пролезть на сцену
rus_verbs:откладывать{}, // откладывать на черный день
rus_verbs:распадаться{}, // распадаться на небольшие фрагменты
rus_verbs:перечислить{}, // перечислить на счет
rus_verbs:закачаться{}, // закачаться на верхний уровень
rus_verbs:накрениться{}, // накрениться на правый борт
rus_verbs:подвинуться{}, // подвинуться на один уровень
rus_verbs:разнести{}, // разнести на мелкие кусочки
rus_verbs:зажить{}, // зажить на широкую ногу
rus_verbs:оглохнуть{}, // оглохнуть на правое ухо
rus_verbs:посетовать{}, // посетовать на бюрократизм
rus_verbs:уводить{}, // уводить на осмотр
rus_verbs:ускакать{}, // ускакать на забег
rus_verbs:посветить{}, // посветить на стену
rus_verbs:разрываться{}, // разрываться на части
rus_verbs:побросать{}, // побросать на землю
rus_verbs:карабкаться{}, // карабкаться на скалу
rus_verbs:нахлынуть{}, // нахлынуть на кого-то
rus_verbs:разлетаться{}, // разлетаться на мелкие осколочки
rus_verbs:среагировать{}, // среагировать на сигнал
rus_verbs:претендовать{}, // претендовать на приз
rus_verbs:дунуть{}, // дунуть на одуванчик
rus_verbs:переводиться{}, // переводиться на другую работу
rus_verbs:перевезти{}, // перевезти на другую площадку
rus_verbs:топать{}, // топать на урок
rus_verbs:относить{}, // относить на склад
rus_verbs:сбивать{}, // сбивать на землю
rus_verbs:укладывать{}, // укладывать на спину
rus_verbs:укатить{}, // укатить на отдых
rus_verbs:убирать{}, // убирать на полку
rus_verbs:опасть{}, // опасть на землю
rus_verbs:ронять{}, // ронять на снег
rus_verbs:пялиться{}, // пялиться на тело
rus_verbs:глазеть{}, // глазеть на тело
rus_verbs:снижаться{}, // снижаться на безопасную высоту
rus_verbs:запрыгнуть{}, // запрыгнуть на платформу
rus_verbs:разбиваться{}, // разбиваться на главы
rus_verbs:сгодиться{}, // сгодиться на фарш
rus_verbs:перескочить{}, // перескочить на другую страницу
rus_verbs:нацелиться{}, // нацелиться на главную добычу
rus_verbs:заезжать{}, // заезжать на бордюр
rus_verbs:забираться{}, // забираться на крышу
rus_verbs:проорать{}, // проорать на всё село
rus_verbs:сбежаться{}, // сбежаться на шум
rus_verbs:сменять{}, // сменять на хлеб
rus_verbs:мотать{}, // мотать на ус
rus_verbs:раскалываться{}, // раскалываться на две половинки
rus_verbs:коситься{}, // коситься на режиссёра
rus_verbs:плевать{}, // плевать на законы
rus_verbs:ссылаться{}, // ссылаться на авторитетное мнение
rus_verbs:наставить{}, // наставить на путь истинный
rus_verbs:завывать{}, // завывать на Луну
rus_verbs:опаздывать{}, // опаздывать на совещание
rus_verbs:залюбоваться{}, // залюбоваться на пейзаж
rus_verbs:повергнуть{}, // повергнуть на землю
rus_verbs:надвинуть{}, // надвинуть на лоб
rus_verbs:стекаться{}, // стекаться на площадь
rus_verbs:обозлиться{}, // обозлиться на тренера
rus_verbs:оттянуть{}, // оттянуть на себя
rus_verbs:истратить{}, // истратить на дешевых шлюх
rus_verbs:вышвырнуть{}, // вышвырнуть на улицу
rus_verbs:затолкать{}, // затолкать на верхнюю полку
rus_verbs:заскочить{}, // заскочить на огонек
rus_verbs:проситься{}, // проситься на улицу
rus_verbs:натыкаться{}, // натыкаться на борщевик
rus_verbs:обрушиваться{}, // обрушиваться на митингующих
rus_verbs:переписать{}, // переписать на чистовик
rus_verbs:переноситься{}, // переноситься на другое устройство
rus_verbs:напроситься{}, // напроситься на обидный ответ
rus_verbs:натягивать{}, // натягивать на ноги
rus_verbs:кидаться{}, // кидаться на прохожих
rus_verbs:откликаться{}, // откликаться на призыв
rus_verbs:поспевать{}, // поспевать на балет
rus_verbs:обратиться{}, // обратиться на кафедру
rus_verbs:полюбоваться{}, // полюбоваться на бюст
rus_verbs:таращиться{}, // таращиться на мустангов
rus_verbs:напороться{}, // напороться на колючки
rus_verbs:раздать{}, // раздать на руки
rus_verbs:дивиться{}, // дивиться на танцовщиц
rus_verbs:назначать{}, // назначать на ответственнейший пост
rus_verbs:кидать{}, // кидать на балкон
rus_verbs:нахлобучить{}, // нахлобучить на башку
rus_verbs:увлекать{}, // увлекать на луг
rus_verbs:ругнуться{}, // ругнуться на животину
rus_verbs:переселиться{}, // переселиться на хутор
rus_verbs:разрывать{}, // разрывать на части
rus_verbs:утащить{}, // утащить на дерево
rus_verbs:наставлять{}, // наставлять на путь
rus_verbs:соблазнить{}, // соблазнить на обмен
rus_verbs:накладывать{}, // накладывать на рану
rus_verbs:набрести{}, // набрести на грибную поляну
rus_verbs:наведываться{}, // наведываться на прежнюю работу
rus_verbs:погулять{}, // погулять на чужие деньги
rus_verbs:уклоняться{}, // уклоняться на два градуса влево
rus_verbs:слезать{}, // слезать на землю
rus_verbs:клевать{}, // клевать на мотыля
// rus_verbs:назначаться{}, // назначаться на пост
rus_verbs:напялить{}, // напялить на голову
rus_verbs:натянуться{}, // натянуться на рамку
rus_verbs:разгневаться{}, // разгневаться на придворных
rus_verbs:эмигрировать{}, // эмигрировать на Кипр
rus_verbs:накатить{}, // накатить на основу
rus_verbs:пригнать{}, // пригнать на пастбище
rus_verbs:обречь{}, // обречь на мучения
rus_verbs:сокращаться{}, // сокращаться на четверть
rus_verbs:оттеснить{}, // оттеснить на пристань
rus_verbs:подбить{}, // подбить на аферу
rus_verbs:заманить{}, // заманить на дерево
инфинитив:пописать{ aux stress="поп^исать" }, глагол:пописать{ aux stress="поп^исать" }, // пописать на кустик
// деепричастие:пописав{ aux stress="поп^исать" },
rus_verbs:посходить{}, // посходить на перрон
rus_verbs:налечь{}, // налечь на мясцо
rus_verbs:отбирать{}, // отбирать на флот
rus_verbs:нашептывать{}, // нашептывать на ухо
rus_verbs:откладываться{}, // откладываться на будущее
rus_verbs:залаять{}, // залаять на грабителя
rus_verbs:настроиться{}, // настроиться на прием
rus_verbs:разбивать{}, // разбивать на куски
rus_verbs:пролиться{}, // пролиться на почву
rus_verbs:сетовать{}, // сетовать на объективные трудности
rus_verbs:подвезти{}, // подвезти на митинг
rus_verbs:припереться{}, // припереться на праздник
rus_verbs:подталкивать{}, // подталкивать на прыжок
rus_verbs:прорываться{}, // прорываться на сцену
rus_verbs:снижать{}, // снижать на несколько процентов
rus_verbs:нацелить{}, // нацелить на танк
rus_verbs:расколоть{}, // расколоть на два куска
rus_verbs:увозить{}, // увозить на обкатку
rus_verbs:оседать{}, // оседать на дно
rus_verbs:съедать{}, // съедать на ужин
rus_verbs:навлечь{}, // навлечь на себя
rus_verbs:равняться{}, // равняться на лучших
rus_verbs:сориентироваться{}, // сориентироваться на местности
rus_verbs:снизить{}, // снизить на несколько процентов
rus_verbs:перенестись{}, // перенестись на много лет назад
rus_verbs:завезти{}, // завезти на склад
rus_verbs:проложить{}, // проложить на гору
rus_verbs:понадеяться{}, // понадеяться на удачу
rus_verbs:заступить{}, // заступить на вахту
rus_verbs:засеменить{}, // засеменить на выход
rus_verbs:запирать{}, // запирать на ключ
rus_verbs:скатываться{}, // скатываться на землю
rus_verbs:дробить{}, // дробить на части
rus_verbs:разваливаться{}, // разваливаться на кусочки
rus_verbs:завозиться{}, // завозиться на склад
rus_verbs:нанимать{}, // нанимать на дневную работу
rus_verbs:поспеть{}, // поспеть на концерт
rus_verbs:променять{}, // променять на сытость
rus_verbs:переправить{}, // переправить на север
rus_verbs:налетать{}, // налетать на силовое поле
rus_verbs:затворить{}, // затворить на замок
rus_verbs:подогнать{}, // подогнать на пристань
rus_verbs:наехать{}, // наехать на камень
rus_verbs:распевать{}, // распевать на разные голоса
rus_verbs:разносить{}, // разносить на клочки
rus_verbs:преувеличивать{}, // преувеличивать на много килограммов
rus_verbs:хромать{}, // хромать на одну ногу
rus_verbs:телеграфировать{}, // телеграфировать на базу
rus_verbs:порезать{}, // порезать на лоскуты
rus_verbs:порваться{}, // порваться на части
rus_verbs:загонять{}, // загонять на дерево
rus_verbs:отбывать{}, // отбывать на место службы
rus_verbs:усаживаться{}, // усаживаться на трон
rus_verbs:накопить{}, // накопить на квартиру
rus_verbs:зыркнуть{}, // зыркнуть на визитера
rus_verbs:копить{}, // копить на машину
rus_verbs:помещать{}, // помещать на верхнюю грань
rus_verbs:сползать{}, // сползать на снег
rus_verbs:попроситься{}, // попроситься на улицу
rus_verbs:перетащить{}, // перетащить на чердак
rus_verbs:растащить{}, // растащить на сувениры
rus_verbs:ниспадать{}, // ниспадать на землю
rus_verbs:сфотографировать{}, // сфотографировать на память
rus_verbs:нагонять{}, // нагонять на конкурентов страх
rus_verbs:покушаться{}, // покушаться на понтифика
rus_verbs:покуситься{},
rus_verbs:наняться{}, // наняться на службу
rus_verbs:просачиваться{}, // просачиваться на поверхность
rus_verbs:пускаться{}, // пускаться на ветер
rus_verbs:отваживаться{}, // отваживаться на прыжок
rus_verbs:досадовать{}, // досадовать на объективные трудности
rus_verbs:унестись{}, // унестись на небо
rus_verbs:ухудшаться{}, // ухудшаться на несколько процентов
rus_verbs:насадить{}, // насадить на копьё
rus_verbs:нагрянуть{}, // нагрянуть на праздник
rus_verbs:зашвырнуть{}, // зашвырнуть на полку
rus_verbs:грешить{}, // грешить на постояльцев
rus_verbs:просочиться{}, // просочиться на поверхность
rus_verbs:надоумить{}, // надоумить на глупость
rus_verbs:намотать{}, // намотать на шпиндель
rus_verbs:замкнуть{}, // замкнуть на корпус
rus_verbs:цыкнуть{}, // цыкнуть на детей
rus_verbs:переворачиваться{}, // переворачиваться на спину
rus_verbs:соваться{}, // соваться на площать
rus_verbs:отлучиться{}, // отлучиться на обед
rus_verbs:пенять{}, // пенять на себя
rus_verbs:нарезать{}, // нарезать на ломтики
rus_verbs:поставлять{}, // поставлять на Кипр
rus_verbs:залезать{}, // залезать на балкон
rus_verbs:отлучаться{}, // отлучаться на обед
rus_verbs:сбиваться{}, // сбиваться на шаг
rus_verbs:таращить{}, // таращить глаза на вошедшего
rus_verbs:прошмыгнуть{}, // прошмыгнуть на кухню
rus_verbs:опережать{}, // опережать на пару сантиметров
rus_verbs:переставить{}, // переставить на стол
rus_verbs:раздирать{}, // раздирать на части
rus_verbs:затвориться{}, // затвориться на засовы
rus_verbs:материться{}, // материться на кого-то
rus_verbs:наскочить{}, // наскочить на риф
rus_verbs:набираться{}, // набираться на борт
rus_verbs:покрикивать{}, // покрикивать на помощников
rus_verbs:заменяться{}, // заменяться на более новый
rus_verbs:подсадить{}, // подсадить на верхнюю полку
rus_verbs:проковылять{}, // проковылять на кухню
rus_verbs:прикатить{}, // прикатить на старт
rus_verbs:залететь{}, // залететь на чужую территорию
rus_verbs:загрузить{}, // загрузить на конвейер
rus_verbs:уплывать{}, // уплывать на материк
rus_verbs:опозорить{}, // опозорить на всю деревню
rus_verbs:провоцировать{}, // провоцировать на ответную агрессию
rus_verbs:забивать{}, // забивать на учебу
rus_verbs:набегать{}, // набегать на прибрежные деревни
rus_verbs:запираться{}, // запираться на ключ
rus_verbs:фотографировать{}, // фотографировать на мыльницу
rus_verbs:подымать{}, // подымать на недосягаемую высоту
rus_verbs:съезжаться{}, // съезжаться на симпозиум
rus_verbs:отвлекаться{}, // отвлекаться на игру
rus_verbs:проливать{}, // проливать на брюки
rus_verbs:спикировать{}, // спикировать на зазевавшегося зайца
rus_verbs:уползти{}, // уползти на вершину холма
rus_verbs:переместить{}, // переместить на вторую палубу
rus_verbs:превысить{}, // превысить на несколько метров
rus_verbs:передвинуться{}, // передвинуться на соседнюю клетку
rus_verbs:спровоцировать{}, // спровоцировать на бросок
rus_verbs:сместиться{}, // сместиться на соседнюю клетку
rus_verbs:заготовить{}, // заготовить на зиму
rus_verbs:плеваться{}, // плеваться на пол
rus_verbs:переселить{}, // переселить на север
rus_verbs:напирать{}, // напирать на дверь
rus_verbs:переезжать{}, // переезжать на другой этаж
rus_verbs:приподнимать{}, // приподнимать на несколько сантиметров
rus_verbs:трогаться{}, // трогаться на красный свет
rus_verbs:надвинуться{}, // надвинуться на глаза
rus_verbs:засмотреться{}, // засмотреться на купальники
rus_verbs:убыть{}, // убыть на фронт
rus_verbs:передвигать{}, // передвигать на второй уровень
rus_verbs:отвозить{}, // отвозить на свалку
rus_verbs:обрекать{}, // обрекать на гибель
rus_verbs:записываться{}, // записываться на танцы
rus_verbs:настраивать{}, // настраивать на другой диапазон
rus_verbs:переписывать{}, // переписывать на диск
rus_verbs:израсходовать{}, // израсходовать на гонки
rus_verbs:обменять{}, // обменять на перспективного игрока
rus_verbs:трубить{}, // трубить на всю округу
rus_verbs:набрасываться{}, // набрасываться на жертву
rus_verbs:чихать{}, // чихать на правила
rus_verbs:наваливаться{}, // наваливаться на рычаг
rus_verbs:сподобиться{}, // сподобиться на повторный анализ
rus_verbs:намазать{}, // намазать на хлеб
rus_verbs:прореагировать{}, // прореагировать на вызов
rus_verbs:зачислить{}, // зачислить на факультет
rus_verbs:наведаться{}, // наведаться на склад
rus_verbs:откидываться{}, // откидываться на спинку кресла
rus_verbs:захромать{}, // захромать на левую ногу
rus_verbs:перекочевать{}, // перекочевать на другой берег
rus_verbs:накатываться{}, // накатываться на песчаный берег
rus_verbs:приостановить{}, // приостановить на некоторое время
rus_verbs:запрятать{}, // запрятать на верхнюю полочку
rus_verbs:прихрамывать{}, // прихрамывать на правую ногу
rus_verbs:упорхнуть{}, // упорхнуть на свободу
rus_verbs:расстегивать{}, // расстегивать на пальто
rus_verbs:напуститься{}, // напуститься на бродягу
rus_verbs:накатывать{}, // накатывать на оригинал
rus_verbs:наезжать{}, // наезжать на простофилю
rus_verbs:тявкнуть{}, // тявкнуть на подошедшего человека
rus_verbs:отрядить{}, // отрядить на починку
rus_verbs:положиться{}, // положиться на главаря
rus_verbs:опрокидывать{}, // опрокидывать на голову
rus_verbs:поторапливаться{}, // поторапливаться на рейс
rus_verbs:налагать{}, // налагать на заемщика
rus_verbs:скопировать{}, // скопировать на диск
rus_verbs:опадать{}, // опадать на землю
rus_verbs:купиться{}, // купиться на посулы
rus_verbs:гневаться{}, // гневаться на слуг
rus_verbs:слететься{}, // слететься на раздачу
rus_verbs:убавить{}, // убавить на два уровня
rus_verbs:спихнуть{}, // спихнуть на соседа
rus_verbs:накричать{}, // накричать на ребенка
rus_verbs:приберечь{}, // приберечь на ужин
rus_verbs:приклеить{}, // приклеить на ветровое стекло
rus_verbs:ополчиться{}, // ополчиться на посредников
rus_verbs:тратиться{}, // тратиться на сувениры
rus_verbs:слетаться{}, // слетаться на свет
rus_verbs:доставляться{}, // доставляться на базу
rus_verbs:поплевать{}, // поплевать на руки
rus_verbs:огрызаться{}, // огрызаться на замечание
rus_verbs:попереться{}, // попереться на рынок
rus_verbs:растягиваться{}, // растягиваться на полу
rus_verbs:повергать{}, // повергать на землю
rus_verbs:ловиться{}, // ловиться на мотыля
rus_verbs:наседать{}, // наседать на обороняющихся
rus_verbs:развалить{}, // развалить на кирпичи
rus_verbs:разломить{}, // разломить на несколько частей
rus_verbs:примерить{}, // примерить на себя
rus_verbs:лепиться{}, // лепиться на стену
rus_verbs:скопить{}, // скопить на старость
rus_verbs:затратить{}, // затратить на ликвидацию последствий
rus_verbs:притащиться{}, // притащиться на гулянку
rus_verbs:осерчать{}, // осерчать на прислугу
rus_verbs:натравить{}, // натравить на медведя
rus_verbs:ссыпать{}, // ссыпать на землю
rus_verbs:подвозить{}, // подвозить на пристань
rus_verbs:мобилизовать{}, // мобилизовать на сборы
rus_verbs:смотаться{}, // смотаться на работу
rus_verbs:заглядеться{}, // заглядеться на девчонок
rus_verbs:таскаться{}, // таскаться на работу
rus_verbs:разгружать{}, // разгружать на транспортер
rus_verbs:потреблять{}, // потреблять на кондиционирование
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять на базу
деепричастие:сгоняв{},
rus_verbs:посылаться{}, // посылаться на разведку
rus_verbs:окрыситься{}, // окрыситься на кого-то
rus_verbs:отлить{}, // отлить на сковороду
rus_verbs:шикнуть{}, // шикнуть на детишек
rus_verbs:уповать{}, // уповать на бескорысную помощь
rus_verbs:класться{}, // класться на стол
rus_verbs:поковылять{}, // поковылять на выход
rus_verbs:навевать{}, // навевать на собравшихся скуку
rus_verbs:накладываться{}, // накладываться на грунтовку
rus_verbs:наноситься{}, // наноситься на чистую кожу
// rus_verbs:запланировать{}, // запланировать на среду
rus_verbs:кувыркнуться{}, // кувыркнуться на землю
rus_verbs:гавкнуть{}, // гавкнуть на хозяина
rus_verbs:перестроиться{}, // перестроиться на новый лад
rus_verbs:расходоваться{}, // расходоваться на образование
rus_verbs:дуться{}, // дуться на бабушку
rus_verbs:перетаскивать{}, // перетаскивать на рабочий стол
rus_verbs:издаться{}, // издаться на деньги спонсоров
rus_verbs:смещаться{}, // смещаться на несколько миллиметров
rus_verbs:зазывать{}, // зазывать на новогоднюю распродажу
rus_verbs:пикировать{}, // пикировать на окопы
rus_verbs:чертыхаться{}, // чертыхаться на мешающихся детей
rus_verbs:зудить{}, // зудить на ухо
rus_verbs:подразделяться{}, // подразделяться на группы
rus_verbs:изливаться{}, // изливаться на землю
rus_verbs:помочиться{}, // помочиться на траву
rus_verbs:примерять{}, // примерять на себя
rus_verbs:разрядиться{}, // разрядиться на землю
rus_verbs:мотнуться{}, // мотнуться на крышу
rus_verbs:налегать{}, // налегать на весла
rus_verbs:зацокать{}, // зацокать на куриц
rus_verbs:наниматься{}, // наниматься на корабль
rus_verbs:сплевывать{}, // сплевывать на землю
rus_verbs:настучать{}, // настучать на саботажника
rus_verbs:приземляться{}, // приземляться на брюхо
rus_verbs:наталкиваться{}, // наталкиваться на объективные трудности
rus_verbs:посигналить{}, // посигналить нарушителю, выехавшему на встречную полосу
rus_verbs:серчать{}, // серчать на нерасторопную помощницу
rus_verbs:сваливать{}, // сваливать на подоконник
rus_verbs:засобираться{}, // засобираться на работу
rus_verbs:распилить{}, // распилить на одинаковые бруски
//rus_verbs:умножать{}, // умножать на константу
rus_verbs:копировать{}, // копировать на диск
rus_verbs:накрутить{}, // накрутить на руку
rus_verbs:навалить{}, // навалить на телегу
rus_verbs:натолкнуть{}, // натолкнуть на свежую мысль
rus_verbs:шлепаться{}, // шлепаться на бетон
rus_verbs:ухлопать{}, // ухлопать на скупку произведений искусства
rus_verbs:замахиваться{}, // замахиваться на авторитетнейшее мнение
rus_verbs:посягнуть{}, // посягнуть на святое
rus_verbs:разменять{}, // разменять на мелочь
rus_verbs:откатываться{}, // откатываться на заранее подготовленные позиции
rus_verbs:усаживать{}, // усаживать на скамейку
rus_verbs:натаскать{}, // натаскать на поиск наркотиков
rus_verbs:зашикать{}, // зашикать на кошку
rus_verbs:разломать{}, // разломать на равные части
rus_verbs:приглашаться{}, // приглашаться на сцену
rus_verbs:присягать{}, // присягать на верность
rus_verbs:запрограммировать{}, // запрограммировать на постоянную уборку
rus_verbs:расщедриться{}, // расщедриться на новый компьютер
rus_verbs:насесть{}, // насесть на двоечников
rus_verbs:созывать{}, // созывать на собрание
rus_verbs:позариться{}, // позариться на чужое добро
rus_verbs:перекидываться{}, // перекидываться на соседние здания
rus_verbs:наползать{}, // наползать на неповрежденную ткань
rus_verbs:изрубить{}, // изрубить на мелкие кусочки
rus_verbs:наворачиваться{}, // наворачиваться на глаза
rus_verbs:раскричаться{}, // раскричаться на всю округу
rus_verbs:переползти{}, // переползти на светлую сторону
rus_verbs:уполномочить{}, // уполномочить на разведовательную операцию
rus_verbs:мочиться{}, // мочиться на трупы убитых врагов
rus_verbs:радировать{}, // радировать на базу
rus_verbs:промотать{}, // промотать на начало
rus_verbs:заснять{}, // заснять на видео
rus_verbs:подбивать{}, // подбивать на матч-реванш
rus_verbs:наплевать{}, // наплевать на справедливость
rus_verbs:подвывать{}, // подвывать на луну
rus_verbs:расплескать{}, // расплескать на пол
rus_verbs:польститься{}, // польститься на бесплатный сыр
rus_verbs:помчать{}, // помчать на работу
rus_verbs:съезжать{}, // съезжать на обочину
rus_verbs:нашептать{}, // нашептать кому-то на ухо
rus_verbs:наклеить{}, // наклеить на доску объявлений
rus_verbs:завозить{}, // завозить на склад
rus_verbs:заявляться{}, // заявляться на любимую работу
rus_verbs:наглядеться{}, // наглядеться на воробьев
rus_verbs:хлопнуться{}, // хлопнуться на живот
rus_verbs:забредать{}, // забредать на поляну
rus_verbs:посягать{}, // посягать на исконные права собственности
rus_verbs:сдвигать{}, // сдвигать на одну позицию
rus_verbs:спрыгивать{}, // спрыгивать на землю
rus_verbs:сдвигаться{}, // сдвигаться на две позиции
rus_verbs:разделать{}, // разделать на орехи
rus_verbs:разлагать{}, // разлагать на элементарные элементы
rus_verbs:обрушивать{}, // обрушивать на головы врагов
rus_verbs:натечь{}, // натечь на пол
rus_verbs:политься{}, // вода польется на землю
rus_verbs:успеть{}, // Они успеют на поезд.
инфинитив:мигрировать{ вид:несоверш }, глагол:мигрировать{ вид:несоверш },
деепричастие:мигрируя{},
инфинитив:мигрировать{ вид:соверш }, глагол:мигрировать{ вид:соверш },
деепричастие:мигрировав{},
rus_verbs:двинуться{}, // Мы скоро двинемся на дачу.
rus_verbs:подойти{}, // Он не подойдёт на должность секретаря.
rus_verbs:потянуть{}, // Он не потянет на директора.
rus_verbs:тянуть{}, // Он не тянет на директора.
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:жаловаться{}, // Он жалуется на нездоровье.
rus_verbs:издать{}, // издать на деньги спонсоров
rus_verbs:показаться{}, // показаться на глаза
rus_verbs:высаживать{}, // высаживать на необитаемый остров
rus_verbs:вознестись{}, // вознестись на самую вершину славы
rus_verbs:залить{}, // залить на youtube
rus_verbs:закачать{}, // закачать на youtube
rus_verbs:сыграть{}, // сыграть на деньги
rus_verbs:экстраполировать{}, // Формулу можно экстраполировать на случай нескольких переменных
инфинитив:экстраполироваться{ вид:несоверш}, // Ситуация легко экстраполируется на случай нескольких переменных
глагол:экстраполироваться{ вид:несоверш},
инфинитив:экстраполироваться{ вид:соверш},
глагол:экстраполироваться{ вид:соверш},
деепричастие:экстраполируясь{},
инфинитив:акцентировать{вид:соверш}, // оратор акцентировал внимание слушателей на новый аспект проблемы
глагол:акцентировать{вид:соверш},
инфинитив:акцентировать{вид:несоверш},
глагол:акцентировать{вид:несоверш},
прилагательное:акцентировавший{вид:несоверш},
//прилагательное:акцентировавший{вид:соверш},
прилагательное:акцентирующий{},
деепричастие:акцентировав{},
деепричастие:акцентируя{},
rus_verbs:бабахаться{}, // он бабахался на пол
rus_verbs:бабахнуться{}, // мальчил бабахнулся на асфальт
rus_verbs:батрачить{}, // Крестьяне батрачили на хозяина
rus_verbs:бахаться{}, // Наездники бахались на землю
rus_verbs:бахнуться{}, // Наездник опять бахнулся на землю
rus_verbs:благословить{}, // батюшка благословил отрока на подвиг
rus_verbs:благословлять{}, // батюшка благословляет отрока на подвиг
rus_verbs:блевануть{}, // Он блеванул на землю
rus_verbs:блевать{}, // Он блюет на землю
rus_verbs:бухнуться{}, // Наездник бухнулся на землю
rus_verbs:валить{}, // Ветер валил деревья на землю
rus_verbs:спилить{}, // Спиленное дерево валится на землю
rus_verbs:ввезти{}, // Предприятие ввезло товар на таможню
rus_verbs:вдохновить{}, // Фильм вдохновил мальчика на поход в лес
rus_verbs:вдохновиться{}, // Мальчик вдохновился на поход
rus_verbs:вдохновлять{}, // Фильм вдохновляет на поход в лес
rus_verbs:вестись{}, // Не ведись на эти уловки!
rus_verbs:вешать{}, // Гости вешают одежду на вешалку
rus_verbs:вешаться{}, // Одежда вешается на вешалки
rus_verbs:вещать{}, // радиостанция вещает на всю страну
rus_verbs:взбираться{}, // Туристы взбираются на заросший лесом холм
rus_verbs:взбредать{}, // Что иногда взбредает на ум
rus_verbs:взбрести{}, // Что-то взбрело на ум
rus_verbs:взвалить{}, // Мама взвалила на свои плечи всё домашнее хозяйство
rus_verbs:взваливаться{}, // Все домашнее хозяйство взваливается на мамины плечи
rus_verbs:взваливать{}, // Не надо взваливать всё на мои плечи
rus_verbs:взглянуть{}, // Кошка взглянула на мышку
rus_verbs:взгромождать{}, // Мальчик взгромождает стул на стол
rus_verbs:взгромождаться{}, // Мальчик взгромождается на стол
rus_verbs:взгромоздить{}, // Мальчик взгромоздил стул на стол
rus_verbs:взгромоздиться{}, // Мальчик взгромоздился на стул
rus_verbs:взирать{}, // Очевидцы взирали на непонятный объект
rus_verbs:взлетать{}, // Фабрика фейерверков взлетает на воздух
rus_verbs:взлететь{}, // Фабрика фейерверков взлетела на воздух
rus_verbs:взобраться{}, // Туристы взобрались на гору
rus_verbs:взойти{}, // Туристы взошли на гору
rus_verbs:взъесться{}, // Отец взъелся на непутевого сына
rus_verbs:взъяриться{}, // Отец взъярился на непутевого сына
rus_verbs:вкатить{}, // рабочие вкатили бочку на пандус
rus_verbs:вкатывать{}, // рабочик вкатывают бочку на пандус
rus_verbs:влиять{}, // Это решение влияет на всех игроков рынка
rus_verbs:водворить{}, // водворить нарушителя на место
rus_verbs:водвориться{}, // водвориться на свое место
rus_verbs:водворять{}, // водворять вещь на свое место
rus_verbs:водворяться{}, // водворяться на свое место
rus_verbs:водружать{}, // водружать флаг на флагшток
rus_verbs:водружаться{}, // Флаг водружается на флагшток
rus_verbs:водрузить{}, // водрузить флаг на флагшток
rus_verbs:водрузиться{}, // Флаг водрузился на вершину горы
rus_verbs:воздействовать{}, // Излучение воздействует на кожу
rus_verbs:воззреть{}, // воззреть на поле боя
rus_verbs:воззриться{}, // воззриться на поле боя
rus_verbs:возить{}, // возить туристов на гору
rus_verbs:возлагать{}, // Многочисленные посетители возлагают цветы на могилу
rus_verbs:возлагаться{}, // Ответственность возлагается на начальство
rus_verbs:возлечь{}, // возлечь на лежанку
rus_verbs:возложить{}, // возложить цветы на могилу поэта
rus_verbs:вознести{}, // вознести кого-то на вершину славы
rus_verbs:возноситься{}, // возносится на вершину успеха
rus_verbs:возносить{}, // возносить счастливчика на вершину успеха
rus_verbs:подниматься{}, // Мы поднимаемся на восьмой этаж
rus_verbs:подняться{}, // Мы поднялись на восьмой этаж
rus_verbs:вонять{}, // Кусок сыра воняет на всю округу
rus_verbs:воодушевлять{}, // Идеалы воодушевляют на подвиги
rus_verbs:воодушевляться{}, // Люди воодушевляются на подвиги
rus_verbs:ворчать{}, // Старый пес ворчит на прохожих
rus_verbs:воспринимать{}, // воспринимать сообщение на слух
rus_verbs:восприниматься{}, // сообщение плохо воспринимается на слух
rus_verbs:воспринять{}, // воспринять сообщение на слух
rus_verbs:восприняться{}, // восприняться на слух
rus_verbs:воссесть{}, // Коля воссел на трон
rus_verbs:вправить{}, // вправить мозг на место
rus_verbs:вправлять{}, // вправлять мозги на место
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:врубать{}, // врубать на полную мощность
rus_verbs:врубить{}, // врубить на полную мощность
rus_verbs:врубиться{}, // врубиться на полную мощность
rus_verbs:врываться{}, // врываться на собрание
rus_verbs:вскарабкаться{}, // вскарабкаться на утёс
rus_verbs:вскарабкиваться{}, // вскарабкиваться на утёс
rus_verbs:вскочить{}, // вскочить на ноги
rus_verbs:всплывать{}, // всплывать на поверхность воды
rus_verbs:всплыть{}, // всплыть на поверхность воды
rus_verbs:вспрыгивать{}, // вспрыгивать на платформу
rus_verbs:вспрыгнуть{}, // вспрыгнуть на платформу
rus_verbs:встать{}, // встать на защиту чести и достоинства
rus_verbs:вторгаться{}, // вторгаться на чужую территорию
rus_verbs:вторгнуться{}, // вторгнуться на чужую территорию
rus_verbs:въезжать{}, // въезжать на пандус
rus_verbs:наябедничать{}, // наябедничать на соседа по парте
rus_verbs:выблевать{}, // выблевать завтрак на пол
rus_verbs:выблеваться{}, // выблеваться на пол
rus_verbs:выблевывать{}, // выблевывать завтрак на пол
rus_verbs:выблевываться{}, // выблевываться на пол
rus_verbs:вывезти{}, // вывезти мусор на свалку
rus_verbs:вывесить{}, // вывесить белье на просушку
rus_verbs:вывести{}, // вывести собаку на прогулку
rus_verbs:вывешивать{}, // вывешивать белье на веревку
rus_verbs:вывозить{}, // вывозить детей на природу
rus_verbs:вызывать{}, // Начальник вызывает на ковер
rus_verbs:выйти{}, // выйти на свободу
rus_verbs:выкладывать{}, // выкладывать на всеобщее обозрение
rus_verbs:выкладываться{}, // выкладываться на всеобщее обозрение
rus_verbs:выливать{}, // выливать на землю
rus_verbs:выливаться{}, // выливаться на землю
rus_verbs:вылить{}, // вылить жидкость на землю
rus_verbs:вылиться{}, // Топливо вылилось на землю
rus_verbs:выложить{}, // выложить на берег
rus_verbs:выменивать{}, // выменивать золото на хлеб
rus_verbs:вымениваться{}, // Золото выменивается на хлеб
rus_verbs:выменять{}, // выменять золото на хлеб
rus_verbs:выпадать{}, // снег выпадает на землю
rus_verbs:выплевывать{}, // выплевывать на землю
rus_verbs:выплевываться{}, // выплевываться на землю
rus_verbs:выплескать{}, // выплескать на землю
rus_verbs:выплескаться{}, // выплескаться на землю
rus_verbs:выплескивать{}, // выплескивать на землю
rus_verbs:выплескиваться{}, // выплескиваться на землю
rus_verbs:выплывать{}, // выплывать на поверхность
rus_verbs:выплыть{}, // выплыть на поверхность
rus_verbs:выплюнуть{}, // выплюнуть на пол
rus_verbs:выползать{}, // выползать на свежий воздух
rus_verbs:выпроситься{}, // выпроситься на улицу
rus_verbs:выпрыгивать{}, // выпрыгивать на свободу
rus_verbs:выпрыгнуть{}, // выпрыгнуть на перрон
rus_verbs:выпускать{}, // выпускать на свободу
rus_verbs:выпустить{}, // выпустить на свободу
rus_verbs:выпучивать{}, // выпучивать на кого-то глаза
rus_verbs:выпучиваться{}, // глаза выпучиваются на кого-то
rus_verbs:выпучить{}, // выпучить глаза на кого-то
rus_verbs:выпучиться{}, // выпучиться на кого-то
rus_verbs:выронить{}, // выронить на землю
rus_verbs:высадить{}, // высадить на берег
rus_verbs:высадиться{}, // высадиться на берег
rus_verbs:высаживаться{}, // высаживаться на остров
rus_verbs:выскальзывать{}, // выскальзывать на землю
rus_verbs:выскочить{}, // выскочить на сцену
rus_verbs:высморкаться{}, // высморкаться на землю
rus_verbs:высморкнуться{}, // высморкнуться на землю
rus_verbs:выставить{}, // выставить на всеобщее обозрение
rus_verbs:выставиться{}, // выставиться на всеобщее обозрение
rus_verbs:выставлять{}, // выставлять на всеобщее обозрение
rus_verbs:выставляться{}, // выставляться на всеобщее обозрение
инфинитив:высыпать{вид:соверш}, // высыпать на землю
инфинитив:высыпать{вид:несоверш},
глагол:высыпать{вид:соверш},
глагол:высыпать{вид:несоверш},
деепричастие:высыпав{},
деепричастие:высыпая{},
прилагательное:высыпавший{вид:соверш},
//++прилагательное:высыпавший{вид:несоверш},
прилагательное:высыпающий{вид:несоверш},
rus_verbs:высыпаться{}, // высыпаться на землю
rus_verbs:вытаращивать{}, // вытаращивать глаза на медведя
rus_verbs:вытаращиваться{}, // вытаращиваться на медведя
rus_verbs:вытаращить{}, // вытаращить глаза на медведя
rus_verbs:вытаращиться{}, // вытаращиться на медведя
rus_verbs:вытекать{}, // вытекать на землю
rus_verbs:вытечь{}, // вытечь на землю
rus_verbs:выучиваться{}, // выучиваться на кого-то
rus_verbs:выучиться{}, // выучиться на кого-то
rus_verbs:посмотреть{}, // посмотреть на экран
rus_verbs:нашить{}, // нашить что-то на одежду
rus_verbs:придти{}, // придти на помощь кому-то
инфинитив:прийти{}, // прийти на помощь кому-то
глагол:прийти{},
деепричастие:придя{}, // Придя на вокзал, он поспешно взял билеты.
rus_verbs:поднять{}, // поднять на вершину
rus_verbs:согласиться{}, // согласиться на ничью
rus_verbs:послать{}, // послать на фронт
rus_verbs:слать{}, // слать на фронт
rus_verbs:надеяться{}, // надеяться на лучшее
rus_verbs:крикнуть{}, // крикнуть на шалунов
rus_verbs:пройти{}, // пройти на пляж
rus_verbs:прислать{}, // прислать на экспертизу
rus_verbs:жить{}, // жить на подачки
rus_verbs:становиться{}, // становиться на ноги
rus_verbs:наслать{}, // наслать на кого-то
rus_verbs:принять{}, // принять на заметку
rus_verbs:собираться{}, // собираться на экзамен
rus_verbs:оставить{}, // оставить на всякий случай
rus_verbs:звать{}, // звать на помощь
rus_verbs:направиться{}, // направиться на прогулку
rus_verbs:отвечать{}, // отвечать на звонки
rus_verbs:отправиться{}, // отправиться на прогулку
rus_verbs:поставить{}, // поставить на пол
rus_verbs:обернуться{}, // обернуться на зов
rus_verbs:отозваться{}, // отозваться на просьбу
rus_verbs:закричать{}, // закричать на собаку
rus_verbs:опустить{}, // опустить на землю
rus_verbs:принести{}, // принести на пляж свой жезлонг
rus_verbs:указать{}, // указать на дверь
rus_verbs:ходить{}, // ходить на занятия
rus_verbs:уставиться{}, // уставиться на листок
rus_verbs:приходить{}, // приходить на экзамен
rus_verbs:махнуть{}, // махнуть на пляж
rus_verbs:явиться{}, // явиться на допрос
rus_verbs:оглянуться{}, // оглянуться на дорогу
rus_verbs:уехать{}, // уехать на заработки
rus_verbs:повести{}, // повести на штурм
rus_verbs:опуститься{}, // опуститься на колени
//rus_verbs:передать{}, // передать на проверку
rus_verbs:побежать{}, // побежать на занятия
rus_verbs:прибыть{}, // прибыть на место службы
rus_verbs:кричать{}, // кричать на медведя
rus_verbs:стечь{}, // стечь на землю
rus_verbs:обратить{}, // обратить на себя внимание
rus_verbs:подать{}, // подать на пропитание
rus_verbs:привести{}, // привести на съемки
rus_verbs:испытывать{}, // испытывать на животных
rus_verbs:перевести{}, // перевести на жену
rus_verbs:купить{}, // купить на заемные деньги
rus_verbs:собраться{}, // собраться на встречу
rus_verbs:заглянуть{}, // заглянуть на огонёк
rus_verbs:нажать{}, // нажать на рычаг
rus_verbs:поспешить{}, // поспешить на праздник
rus_verbs:перейти{}, // перейти на русский язык
rus_verbs:поверить{}, // поверить на честное слово
rus_verbs:глянуть{}, // глянуть на обложку
rus_verbs:зайти{}, // зайти на огонёк
rus_verbs:проходить{}, // проходить на сцену
rus_verbs:глядеть{}, // глядеть на актрису
//rus_verbs:решиться{}, // решиться на прыжок
rus_verbs:пригласить{}, // пригласить на танец
rus_verbs:позвать{}, // позвать на экзамен
rus_verbs:усесться{}, // усесться на стул
rus_verbs:поступить{}, // поступить на математический факультет
rus_verbs:лечь{}, // лечь на живот
rus_verbs:потянуться{}, // потянуться на юг
rus_verbs:присесть{}, // присесть на корточки
rus_verbs:наступить{}, // наступить на змею
rus_verbs:заорать{}, // заорать на попрошаек
rus_verbs:надеть{}, // надеть на голову
rus_verbs:поглядеть{}, // поглядеть на девчонок
rus_verbs:принимать{}, // принимать на гарантийное обслуживание
rus_verbs:привезти{}, // привезти на испытания
rus_verbs:рухнуть{}, // рухнуть на асфальт
rus_verbs:пускать{}, // пускать на корм
rus_verbs:отвести{}, // отвести на приём
rus_verbs:отправить{}, // отправить на утилизацию
rus_verbs:двигаться{}, // двигаться на восток
rus_verbs:нести{}, // нести на пляж
rus_verbs:падать{}, // падать на руки
rus_verbs:откинуться{}, // откинуться на спинку кресла
rus_verbs:рявкнуть{}, // рявкнуть на детей
rus_verbs:получать{}, // получать на проживание
rus_verbs:полезть{}, // полезть на рожон
rus_verbs:направить{}, // направить на дообследование
rus_verbs:приводить{}, // приводить на проверку
rus_verbs:потребоваться{}, // потребоваться на замену
rus_verbs:кинуться{}, // кинуться на нападавшего
rus_verbs:учиться{}, // учиться на токаря
rus_verbs:приподнять{}, // приподнять на один метр
rus_verbs:налить{}, // налить на стол
rus_verbs:играть{}, // играть на деньги
rus_verbs:рассчитывать{}, // рассчитывать на подмогу
rus_verbs:шепнуть{}, // шепнуть на ухо
rus_verbs:швырнуть{}, // швырнуть на землю
rus_verbs:прыгнуть{}, // прыгнуть на оленя
rus_verbs:предлагать{}, // предлагать на выбор
rus_verbs:садиться{}, // садиться на стул
rus_verbs:лить{}, // лить на землю
rus_verbs:испытать{}, // испытать на животных
rus_verbs:фыркнуть{}, // фыркнуть на детеныша
rus_verbs:годиться{}, // мясо годится на фарш
rus_verbs:проверить{}, // проверить высказывание на истинность
rus_verbs:откликнуться{}, // откликнуться на призывы
rus_verbs:полагаться{}, // полагаться на интуицию
rus_verbs:покоситься{}, // покоситься на соседа
rus_verbs:повесить{}, // повесить на гвоздь
инфинитив:походить{вид:соверш}, // походить на занятия
глагол:походить{вид:соверш},
деепричастие:походив{},
прилагательное:походивший{},
rus_verbs:помчаться{}, // помчаться на экзамен
rus_verbs:ставить{}, // ставить на контроль
rus_verbs:свалиться{}, // свалиться на землю
rus_verbs:валиться{}, // валиться на землю
rus_verbs:подарить{}, // подарить на день рожденья
rus_verbs:сбежать{}, // сбежать на необитаемый остров
rus_verbs:стрелять{}, // стрелять на поражение
rus_verbs:обращать{}, // обращать на себя внимание
rus_verbs:наступать{}, // наступать на те же грабли
rus_verbs:сбросить{}, // сбросить на землю
rus_verbs:обидеться{}, // обидеться на друга
rus_verbs:устроиться{}, // устроиться на стажировку
rus_verbs:погрузиться{}, // погрузиться на большую глубину
rus_verbs:течь{}, // течь на землю
rus_verbs:отбросить{}, // отбросить на землю
rus_verbs:метать{}, // метать на дно
rus_verbs:пустить{}, // пустить на переплавку
rus_verbs:прожить{}, // прожить на пособие
rus_verbs:полететь{}, // полететь на континент
rus_verbs:пропустить{}, // пропустить на сцену
rus_verbs:указывать{}, // указывать на ошибку
rus_verbs:наткнуться{}, // наткнуться на клад
rus_verbs:рвануть{}, // рвануть на юг
rus_verbs:ступать{}, // ступать на землю
rus_verbs:спрыгнуть{}, // спрыгнуть на берег
rus_verbs:заходить{}, // заходить на огонёк
rus_verbs:нырнуть{}, // нырнуть на глубину
rus_verbs:рвануться{}, // рвануться на свободу
rus_verbs:натянуть{}, // натянуть на голову
rus_verbs:забраться{}, // забраться на стол
rus_verbs:помахать{}, // помахать на прощание
rus_verbs:содержать{}, // содержать на спонсорскую помощь
rus_verbs:приезжать{}, // приезжать на праздники
rus_verbs:проникнуть{}, // проникнуть на территорию
rus_verbs:подъехать{}, // подъехать на митинг
rus_verbs:устремиться{}, // устремиться на волю
rus_verbs:посадить{}, // посадить на стул
rus_verbs:ринуться{}, // ринуться на голкипера
rus_verbs:подвигнуть{}, // подвигнуть на подвиг
rus_verbs:отдавать{}, // отдавать на перевоспитание
rus_verbs:отложить{}, // отложить на черный день
rus_verbs:убежать{}, // убежать на танцы
rus_verbs:поднимать{}, // поднимать на верхний этаж
rus_verbs:переходить{}, // переходить на цифровой сигнал
rus_verbs:отослать{}, // отослать на переаттестацию
rus_verbs:отодвинуть{}, // отодвинуть на другую половину стола
rus_verbs:назначить{}, // назначить на должность
rus_verbs:осесть{}, // осесть на дно
rus_verbs:торопиться{}, // торопиться на экзамен
rus_verbs:менять{}, // менять на еду
rus_verbs:доставить{}, // доставить на шестой этаж
rus_verbs:заслать{}, // заслать на проверку
rus_verbs:дуть{}, // дуть на воду
rus_verbs:сослать{}, // сослать на каторгу
rus_verbs:останавливаться{}, // останавливаться на отдых
rus_verbs:сдаваться{}, // сдаваться на милость победителя
rus_verbs:сослаться{}, // сослаться на презумпцию невиновности
rus_verbs:рассердиться{}, // рассердиться на дочь
rus_verbs:кинуть{}, // кинуть на землю
rus_verbs:расположиться{}, // расположиться на ночлег
rus_verbs:осмелиться{}, // осмелиться на подлог
rus_verbs:шептать{}, // шептать на ушко
rus_verbs:уронить{}, // уронить на землю
rus_verbs:откинуть{}, // откинуть на спинку кресла
rus_verbs:перенести{}, // перенести на рабочий стол
rus_verbs:сдаться{}, // сдаться на милость победителя
rus_verbs:светить{}, // светить на дорогу
rus_verbs:мчаться{}, // мчаться на бал
rus_verbs:нестись{}, // нестись на свидание
rus_verbs:поглядывать{}, // поглядывать на экран
rus_verbs:орать{}, // орать на детей
rus_verbs:уложить{}, // уложить на лопатки
rus_verbs:решаться{}, // решаться на поступок
rus_verbs:попадать{}, // попадать на карандаш
rus_verbs:сплюнуть{}, // сплюнуть на землю
rus_verbs:снимать{}, // снимать на телефон
rus_verbs:опоздать{}, // опоздать на работу
rus_verbs:посылать{}, // посылать на проверку
rus_verbs:погнать{}, // погнать на пастбище
rus_verbs:поступать{}, // поступать на кибернетический факультет
rus_verbs:спускаться{}, // спускаться на уровень моря
rus_verbs:усадить{}, // усадить на диван
rus_verbs:проиграть{}, // проиграть на спор
rus_verbs:прилететь{}, // прилететь на фестиваль
rus_verbs:повалиться{}, // повалиться на спину
rus_verbs:огрызнуться{}, // Собака огрызнулась на хозяина
rus_verbs:задавать{}, // задавать на выходные
rus_verbs:запасть{}, // запасть на девочку
rus_verbs:лезть{}, // лезть на забор
rus_verbs:потащить{}, // потащить на выборы
rus_verbs:направляться{}, // направляться на экзамен
rus_verbs:определять{}, // определять на вкус
rus_verbs:поползти{}, // поползти на стену
rus_verbs:поплыть{}, // поплыть на берег
rus_verbs:залезть{}, // залезть на яблоню
rus_verbs:сдать{}, // сдать на мясокомбинат
rus_verbs:приземлиться{}, // приземлиться на дорогу
rus_verbs:лаять{}, // лаять на прохожих
rus_verbs:перевернуть{}, // перевернуть на бок
rus_verbs:ловить{}, // ловить на живца
rus_verbs:отнести{}, // отнести животное на хирургический стол
rus_verbs:плюнуть{}, // плюнуть на условности
rus_verbs:передавать{}, // передавать на проверку
rus_verbs:нанять{}, // Босс нанял на работу еще несколько человек
rus_verbs:разозлиться{}, // Папа разозлился на сына из-за плохих оценок по математике
инфинитив:рассыпаться{вид:несоверш}, // рассыпаться на мелкие детали
инфинитив:рассыпаться{вид:соверш},
глагол:рассыпаться{вид:несоверш},
глагол:рассыпаться{вид:соверш},
деепричастие:рассыпавшись{},
деепричастие:рассыпаясь{},
прилагательное:рассыпавшийся{вид:несоверш},
прилагательное:рассыпавшийся{вид:соверш},
прилагательное:рассыпающийся{},
rus_verbs:зарычать{}, // Медведица зарычала на медвежонка
rus_verbs:призвать{}, // призвать на сборы
rus_verbs:увезти{}, // увезти на дачу
rus_verbs:содержаться{}, // содержаться на пожертвования
rus_verbs:навести{}, // навести на скопление телескоп
rus_verbs:отправляться{}, // отправляться на утилизацию
rus_verbs:улечься{}, // улечься на животик
rus_verbs:налететь{}, // налететь на препятствие
rus_verbs:перевернуться{}, // перевернуться на спину
rus_verbs:улететь{}, // улететь на родину
rus_verbs:ложиться{}, // ложиться на бок
rus_verbs:класть{}, // класть на место
rus_verbs:отреагировать{}, // отреагировать на выступление
rus_verbs:доставлять{}, // доставлять на дом
rus_verbs:отнять{}, // отнять на благо правящей верхушки
rus_verbs:ступить{}, // ступить на землю
rus_verbs:сводить{}, // сводить на концерт знаменитой рок-группы
rus_verbs:унести{}, // унести на работу
rus_verbs:сходить{}, // сходить на концерт
rus_verbs:потратить{}, // потратить на корм и наполнитель для туалета все деньги
rus_verbs:соскочить{}, // соскочить на землю
rus_verbs:пожаловаться{}, // пожаловаться на соседей
rus_verbs:тащить{}, // тащить на замену
rus_verbs:замахать{}, // замахать руками на паренька
rus_verbs:заглядывать{}, // заглядывать на обед
rus_verbs:соглашаться{}, // соглашаться на равный обмен
rus_verbs:плюхнуться{}, // плюхнуться на мягкий пуфик
rus_verbs:увести{}, // увести на осмотр
rus_verbs:успевать{}, // успевать на контрольную работу
rus_verbs:опрокинуть{}, // опрокинуть на себя
rus_verbs:подавать{}, // подавать на апелляцию
rus_verbs:прибежать{}, // прибежать на вокзал
rus_verbs:отшвырнуть{}, // отшвырнуть на замлю
rus_verbs:привлекать{}, // привлекать на свою сторону
rus_verbs:опереться{}, // опереться на палку
rus_verbs:перебраться{}, // перебраться на маленький островок
rus_verbs:уговорить{}, // уговорить на новые траты
rus_verbs:гулять{}, // гулять на спонсорские деньги
rus_verbs:переводить{}, // переводить на другой путь
rus_verbs:заколебаться{}, // заколебаться на один миг
rus_verbs:зашептать{}, // зашептать на ушко
rus_verbs:привстать{}, // привстать на цыпочки
rus_verbs:хлынуть{}, // хлынуть на берег
rus_verbs:наброситься{}, // наброситься на еду
rus_verbs:напасть{}, // повстанцы, напавшие на конвой
rus_verbs:убрать{}, // книга, убранная на полку
rus_verbs:попасть{}, // путешественники, попавшие на ничейную территорию
rus_verbs:засматриваться{}, // засматриваться на девчонок
rus_verbs:застегнуться{}, // застегнуться на все пуговицы
rus_verbs:провериться{}, // провериться на заболевания
rus_verbs:проверяться{}, // проверяться на заболевания
rus_verbs:тестировать{}, // тестировать на профпригодность
rus_verbs:протестировать{}, // протестировать на профпригодность
rus_verbs:уходить{}, // отец, уходящий на работу
rus_verbs:налипнуть{}, // снег, налипший на провода
rus_verbs:налипать{}, // снег, налипающий на провода
rus_verbs:улетать{}, // Многие птицы улетают осенью на юг.
rus_verbs:поехать{}, // она поехала на встречу с заказчиком
rus_verbs:переключать{}, // переключать на резервную линию
rus_verbs:переключаться{}, // переключаться на резервную линию
rus_verbs:подписаться{}, // подписаться на обновление
rus_verbs:нанести{}, // нанести на кожу
rus_verbs:нарываться{}, // нарываться на неприятности
rus_verbs:выводить{}, // выводить на орбиту
rus_verbs:вернуться{}, // вернуться на родину
rus_verbs:возвращаться{}, // возвращаться на родину
прилагательное:падкий{}, // Он падок на деньги.
прилагательное:обиженный{}, // Он обижен на отца.
rus_verbs:косить{}, // Он косит на оба глаза.
rus_verbs:закрыть{}, // Он забыл закрыть дверь на замок.
прилагательное:готовый{}, // Он готов на всякие жертвы.
rus_verbs:говорить{}, // Он говорит на скользкую тему.
прилагательное:глухой{}, // Он глух на одно ухо.
rus_verbs:взять{}, // Он взял ребёнка себе на колени.
rus_verbs:оказывать{}, // Лекарство не оказывало на него никакого действия.
rus_verbs:вести{}, // Лестница ведёт на третий этаж.
rus_verbs:уполномочивать{}, // уполномочивать на что-либо
глагол:спешить{ вид:несоверш }, // Я спешу на поезд.
rus_verbs:брать{}, // Я беру всю ответственность на себя.
rus_verbs:произвести{}, // Это произвело на меня глубокое впечатление.
rus_verbs:употребить{}, // Эти деньги можно употребить на ремонт фабрики.
rus_verbs:наводить{}, // Эта песня наводит на меня сон и скуку.
rus_verbs:разбираться{}, // Эта машина разбирается на части.
rus_verbs:оказать{}, // Эта книга оказала на меня большое влияние.
rus_verbs:разбить{}, // Учитель разбил учеников на несколько групп.
rus_verbs:отразиться{}, // Усиленная работа отразилась на его здоровье.
rus_verbs:перегрузить{}, // Уголь надо перегрузить на другое судно.
rus_verbs:делиться{}, // Тридцать делится на пять без остатка.
rus_verbs:удаляться{}, // Суд удаляется на совещание.
rus_verbs:показывать{}, // Стрелка компаса всегда показывает на север.
rus_verbs:сохранить{}, // Сохраните это на память обо мне.
rus_verbs:уезжать{}, // Сейчас все студенты уезжают на экскурсию.
rus_verbs:лететь{}, // Самолёт летит на север.
rus_verbs:бить{}, // Ружьё бьёт на пятьсот метров.
// rus_verbs:прийтись{}, // Пятое число пришлось на субботу.
rus_verbs:вынести{}, // Они вынесли из лодки на берег все вещи.
rus_verbs:смотреть{}, // Она смотрит на нас из окна.
rus_verbs:отдать{}, // Она отдала мне деньги на сохранение.
rus_verbs:налюбоваться{}, // Не могу налюбоваться на картину.
rus_verbs:любоваться{}, // гости любовались на картину
rus_verbs:попробовать{}, // Дайте мне попробовать на ощупь.
прилагательное:действительный{}, // Прививка оспы действительна только на три года.
rus_verbs:спуститься{}, // На город спустился смог
прилагательное:нечистый{}, // Он нечист на руку.
прилагательное:неспособный{}, // Он неспособен на такую низость.
прилагательное:злой{}, // кот очень зол на хозяина
rus_verbs:пойти{}, // Девочка не пошла на урок физультуры
rus_verbs:прибывать{}, // мой поезд прибывает на первый путь
rus_verbs:застегиваться{}, // пальто застегивается на двадцать одну пуговицу
rus_verbs:идти{}, // Дело идёт на лад.
rus_verbs:лазить{}, // Он лазил на чердак.
rus_verbs:поддаваться{}, // Он легко поддаётся на уговоры.
// rus_verbs:действовать{}, // действующий на нервы
rus_verbs:выходить{}, // Балкон выходит на площадь.
rus_verbs:работать{}, // Время работает на нас.
глагол:написать{aux stress="напис^ать"}, // Он написал музыку на слова Пушкина.
rus_verbs:бросить{}, // Они бросили все силы на строительство.
// глагол:разрезать{aux stress="разр^езать"}, глагол:разрезать{aux stress="разрез^ать"}, // Она разрезала пирог на шесть кусков.
rus_verbs:броситься{}, // Она радостно бросилась мне на шею.
rus_verbs:оправдать{}, // Она оправдала неявку на занятия болезнью.
rus_verbs:ответить{}, // Она не ответила на мой поклон.
rus_verbs:нашивать{}, // Она нашивала заплату на локоть.
rus_verbs:молиться{}, // Она молится на свою мать.
rus_verbs:запереть{}, // Она заперла дверь на замок.
rus_verbs:заявить{}, // Она заявила свои права на наследство.
rus_verbs:уйти{}, // Все деньги ушли на путешествие.
rus_verbs:вступить{}, // Водолаз вступил на берег.
rus_verbs:сойти{}, // Ночь сошла на землю.
rus_verbs:приехать{}, // Мы приехали на вокзал слишком рано.
rus_verbs:рыдать{}, // Не рыдай так безумно над ним.
rus_verbs:подписать{}, // Не забудьте подписать меня на газету.
rus_verbs:держать{}, // Наш пароход держал курс прямо на север.
rus_verbs:свезти{}, // На выставку свезли экспонаты со всего мира.
rus_verbs:ехать{}, // Мы сейчас едем на завод.
rus_verbs:выбросить{}, // Волнами лодку выбросило на берег.
ГЛ_ИНФ(сесть), // сесть на снег
ГЛ_ИНФ(записаться),
ГЛ_ИНФ(положить) // положи книгу на стол
}
#endregion VerbList
// Чтобы разрешить связывание в паттернах типа: залить на youtube
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { глагол:купить{} предлог:на{} 'деньги'{падеж:вин} }
then return true
}
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} *:*{ падеж:вин } }
then return true
}
// смещаться на несколько миллиметров
fact гл_предл
{
if context { Гл_НА_Вин предлог:на{} наречие:*{} }
then return true
}
// партия взяла на себя нереалистичные обязательства
fact гл_предл
{
if context { глагол:взять{} предлог:на{} 'себя'{падеж:вин} }
then return true
}
#endregion ВИНИТЕЛЬНЫЙ
// Все остальные варианты с предлогом 'НА' по умолчанию запрещаем.
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:мест } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:вин } }
then return false,-4
}
// Этот вариант нужен для обработки конструкций с числительными:
// Президентские выборы разделили Венесуэлу на два непримиримых лагеря
fact гл_предл
{
if context { * предлог:на{} *:*{ падеж:род } }
then return false,-4
}
// Продавать на eBay
fact гл_предл
{
if context { * предлог:на{} * }
then return false,-6
}
#endregion Предлог_НА
#region Предлог_С
// ------------- ПРЕДЛОГ 'С' -----------------
// У этого предлога предпочтительная семантика привязывает его обычно к существительному.
// Поэтому запрещаем по умолчанию его привязку к глаголам, а разрешенные глаголы перечислим.
#region ТВОРИТЕЛЬНЫЙ
wordentry_set Гл_С_Твор={
rus_verbs:помогать{}, // будет готов помогать врачам в онкологическом центре с постановкой верных диагнозов
rus_verbs:перепихнуться{}, // неужели ты не хочешь со мной перепихнуться
rus_verbs:забраться{},
rus_verbs:ДРАТЬСЯ{}, // Мои же собственные ратники забросали бы меня гнилой капустой, и мне пришлось бы драться с каждым рыцарем в стране, чтобы доказать свою смелость. (ДРАТЬСЯ/БИТЬСЯ/ПОДРАТЬСЯ)
rus_verbs:БИТЬСЯ{}, //
rus_verbs:ПОДРАТЬСЯ{}, //
прилагательное:СХОЖИЙ{}, // Не был ли он схожим с одним из живых языков Земли (СХОЖИЙ)
rus_verbs:ВСТУПИТЬ{}, // Он намеревался вступить с Вольфом в ближний бой. (ВСТУПИТЬ)
rus_verbs:КОРРЕЛИРОВАТЬ{}, // Это коррелирует с традиционно сильными направлениями московской математической школы. (КОРРЕЛИРОВАТЬ)
rus_verbs:УВИДЕТЬСЯ{}, // Он проигнорирует истерические протесты жены и увидится сначала с доктором, а затем с психотерапевтом (УВИДЕТЬСЯ)
rus_verbs:ОЧНУТЬСЯ{}, // Когда он очнулся с болью в левой стороне черепа, у него возникло пугающее ощущение. (ОЧНУТЬСЯ)
прилагательное:сходный{}, // Мозг этих существ сходен по размерам с мозгом динозавра
rus_verbs:накрыться{}, // Было холодно, и он накрылся с головой одеялом.
rus_verbs:РАСПРЕДЕЛИТЬ{}, // Бюджет распределят с участием горожан (РАСПРЕДЕЛИТЬ)
rus_verbs:НАБРОСИТЬСЯ{}, // Пьяный водитель набросился с ножом на сотрудников ГИБДД (НАБРОСИТЬСЯ)
rus_verbs:БРОСИТЬСЯ{}, // она со смехом бросилась прочь (БРОСИТЬСЯ)
rus_verbs:КОНТАКТИРОВАТЬ{}, // Электронным магазинам стоит контактировать с клиентами (КОНТАКТИРОВАТЬ)
rus_verbs:ВИДЕТЬСЯ{}, // Тогда мы редко виделись друг с другом
rus_verbs:сесть{}, // сел в него с дорожной сумкой , наполненной наркотиками
rus_verbs:купить{}, // Мы купили с ним одну и ту же книгу
rus_verbs:ПРИМЕНЯТЬ{}, // Меры по стимулированию спроса в РФ следует применять с осторожностью (ПРИМЕНЯТЬ)
rus_verbs:УЙТИ{}, // ты мог бы уйти со мной (УЙТИ)
rus_verbs:ЖДАТЬ{}, // С нарастающим любопытством ждем результатов аудита золотых хранилищ европейских и американских центробанков (ЖДАТЬ)
rus_verbs:ГОСПИТАЛИЗИРОВАТЬ{}, // Мэра Твери, участвовавшего в спартакиаде, госпитализировали с инфарктом (ГОСПИТАЛИЗИРОВАТЬ)
rus_verbs:ЗАХЛОПНУТЬСЯ{}, // она захлопнулась со звоном (ЗАХЛОПНУТЬСЯ)
rus_verbs:ОТВЕРНУТЬСЯ{}, // она со вздохом отвернулась (ОТВЕРНУТЬСЯ)
rus_verbs:отправить{}, // вы можете отправить со мной человека
rus_verbs:выступать{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам
rus_verbs:ВЫЕЗЖАТЬ{}, // заключенные сами шьют куклы и иногда выезжают с представлениями в детский дом неподалеку (ВЫЕЗЖАТЬ С твор)
rus_verbs:ПОКОНЧИТЬ{}, // со всем этим покончено (ПОКОНЧИТЬ С)
rus_verbs:ПОБЕЖАТЬ{}, // Дмитрий побежал со всеми (ПОБЕЖАТЬ С)
прилагательное:несовместимый{}, // характер ранений был несовместим с жизнью (НЕСОВМЕСТИМЫЙ С)
rus_verbs:ПОСЕТИТЬ{}, // Его кабинет местные тележурналисты посетили со скрытой камерой (ПОСЕТИТЬ С)
rus_verbs:СЛОЖИТЬСЯ{}, // сами банки принимают меры по урегулированию сложившейся с вкладчиками ситуации (СЛОЖИТЬСЯ С)
rus_verbs:ЗАСТАТЬ{}, // Молодой человек убил пенсионера , застав его в постели с женой (ЗАСТАТЬ С)
rus_verbs:ОЗНАКАМЛИВАТЬСЯ{}, // при заполнении заявления владельцы судов ознакамливаются с режимом (ОЗНАКАМЛИВАТЬСЯ С)
rus_verbs:СООБРАЗОВЫВАТЬ{}, // И все свои задачи мы сообразовываем с этим пониманием (СООБРАЗОВЫВАТЬ С)
rus_verbs:СВЫКАТЬСЯ{},
rus_verbs:стаскиваться{},
rus_verbs:спиливаться{},
rus_verbs:КОНКУРИРОВАТЬ{}, // Бедные и менее развитые страны не могут конкурировать с этими субсидиями (КОНКУРИРОВАТЬ С)
rus_verbs:ВЫРВАТЬСЯ{}, // тот с трудом вырвался (ВЫРВАТЬСЯ С твор)
rus_verbs:СОБРАТЬСЯ{}, // нужно собраться с силами (СОБРАТЬСЯ С)
rus_verbs:УДАВАТЬСЯ{}, // удавалось это с трудом (УДАВАТЬСЯ С)
rus_verbs:РАСПАХНУТЬСЯ{}, // дверь с треском распахнулась (РАСПАХНУТЬСЯ С)
rus_verbs:НАБЛЮДАТЬ{}, // Олег наблюдал с любопытством (НАБЛЮДАТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // затем с силой потянул (ПОТЯНУТЬ С)
rus_verbs:КИВНУТЬ{}, // Питер с трудом кивнул (КИВНУТЬ С)
rus_verbs:СГЛОТНУТЬ{}, // Борис с трудом сглотнул (СГЛОТНУТЬ С)
rus_verbs:ЗАБРАТЬ{}, // забрать его с собой (ЗАБРАТЬ С)
rus_verbs:ОТКРЫТЬСЯ{}, // дверь с шипением открылась (ОТКРЫТЬСЯ С)
rus_verbs:ОТОРВАТЬ{}, // с усилием оторвал взгляд (ОТОРВАТЬ С твор)
rus_verbs:ОГЛЯДЕТЬСЯ{}, // Рома с любопытством огляделся (ОГЛЯДЕТЬСЯ С)
rus_verbs:ФЫРКНУТЬ{}, // турок фыркнул с отвращением (ФЫРКНУТЬ С)
rus_verbs:согласиться{}, // с этим согласились все (согласиться с)
rus_verbs:ПОСЫПАТЬСЯ{}, // с грохотом посыпались камни (ПОСЫПАТЬСЯ С твор)
rus_verbs:ВЗДОХНУТЬ{}, // Алиса вздохнула с облегчением (ВЗДОХНУТЬ С)
rus_verbs:ОБЕРНУТЬСЯ{}, // та с удивлением обернулась (ОБЕРНУТЬСЯ С)
rus_verbs:ХМЫКНУТЬ{}, // Алексей хмыкнул с сомнением (ХМЫКНУТЬ С твор)
rus_verbs:ВЫЕХАТЬ{}, // они выехали с рассветом (ВЫЕХАТЬ С твор)
rus_verbs:ВЫДОХНУТЬ{}, // Владимир выдохнул с облегчением (ВЫДОХНУТЬ С)
rus_verbs:УХМЫЛЬНУТЬСЯ{}, // Кеша ухмыльнулся с сомнением (УХМЫЛЬНУТЬСЯ С)
rus_verbs:НЕСТИСЬ{}, // тот несся с криком (НЕСТИСЬ С твор)
rus_verbs:ПАДАТЬ{}, // падают с глухим стуком (ПАДАТЬ С твор)
rus_verbs:ТВОРИТЬСЯ{}, // странное творилось с глазами (ТВОРИТЬСЯ С твор)
rus_verbs:УХОДИТЬ{}, // с ними уходили эльфы (УХОДИТЬ С твор)
rus_verbs:СКАКАТЬ{}, // скакали тут с топорами (СКАКАТЬ С твор)
rus_verbs:ЕСТЬ{}, // здесь едят с зеленью (ЕСТЬ С твор)
rus_verbs:ПОЯВИТЬСЯ{}, // с рассветом появились птицы (ПОЯВИТЬСЯ С твор)
rus_verbs:ВСКОЧИТЬ{}, // Олег вскочил с готовностью (ВСКОЧИТЬ С твор)
rus_verbs:БЫТЬ{}, // хочу быть с тобой (БЫТЬ С твор)
rus_verbs:ПОКАЧАТЬ{}, // с сомнением покачал головой. (ПОКАЧАТЬ С СОМНЕНИЕМ)
rus_verbs:ВЫРУГАТЬСЯ{}, // капитан с чувством выругался (ВЫРУГАТЬСЯ С ЧУВСТВОМ)
rus_verbs:ОТКРЫТЬ{}, // с трудом открыл глаза (ОТКРЫТЬ С ТРУДОМ, таких много)
rus_verbs:ПОЛУЧИТЬСЯ{}, // забавно получилось с ним (ПОЛУЧИТЬСЯ С)
rus_verbs:ВЫБЕЖАТЬ{}, // старый выбежал с копьем (ВЫБЕЖАТЬ С)
rus_verbs:ГОТОВИТЬСЯ{}, // Большинство компотов готовится с использованием сахара (ГОТОВИТЬСЯ С)
rus_verbs:ПОДИСКУТИРОВАТЬ{}, // я бы подискутировал с Андрюхой (ПОДИСКУТИРОВАТЬ С)
rus_verbs:ТУСИТЬ{}, // кто тусил со Светкой (ТУСИТЬ С)
rus_verbs:БЕЖАТЬ{}, // куда она бежит со всеми? (БЕЖАТЬ С твор)
rus_verbs:ГОРЕТЬ{}, // ты горел со своим кораблем? (ГОРЕТЬ С)
rus_verbs:ВЫПИТЬ{}, // хотите выпить со мной чаю? (ВЫПИТЬ С)
rus_verbs:МЕНЯТЬСЯ{}, // Я меняюсь с товарищем книгами. (МЕНЯТЬСЯ С)
rus_verbs:ВАЛЯТЬСЯ{}, // Он уже неделю валяется с гриппом. (ВАЛЯТЬСЯ С)
rus_verbs:ПИТЬ{}, // вы даже будете пить со мной пиво. (ПИТЬ С)
инфинитив:кристаллизоваться{ вид:соверш }, // После этого пересыщенный раствор кристаллизуется с образованием кристаллов сахара.
инфинитив:кристаллизоваться{ вид:несоверш },
глагол:кристаллизоваться{ вид:соверш },
глагол:кристаллизоваться{ вид:несоверш },
rus_verbs:ПООБЩАТЬСЯ{}, // пообщайся с Борисом (ПООБЩАТЬСЯ С)
rus_verbs:ОБМЕНЯТЬСЯ{}, // Миша обменялся с Петей марками (ОБМЕНЯТЬСЯ С)
rus_verbs:ПРОХОДИТЬ{}, // мы с тобой сегодня весь день проходили с вещами. (ПРОХОДИТЬ С)
rus_verbs:ВСТАТЬ{}, // Он занимался всю ночь и встал с головной болью. (ВСТАТЬ С)
rus_verbs:ПОВРЕМЕНИТЬ{}, // МВФ рекомендует Ирландии повременить с мерами экономии (ПОВРЕМЕНИТЬ С)
rus_verbs:ГЛЯДЕТЬ{}, // Её глаза глядели с мягкой грустью. (ГЛЯДЕТЬ С + твор)
rus_verbs:ВЫСКОЧИТЬ{}, // Зачем ты выскочил со своим замечанием? (ВЫСКОЧИТЬ С)
rus_verbs:НЕСТИ{}, // плот несло со страшной силой. (НЕСТИ С)
rus_verbs:приближаться{}, // стена приближалась со страшной быстротой. (приближаться с)
rus_verbs:заниматься{}, // После уроков я занимался с отстающими учениками. (заниматься с)
rus_verbs:разработать{}, // Этот лекарственный препарат разработан с использованием рецептов традиционной китайской медицины. (разработать с)
rus_verbs:вестись{}, // Разработка месторождения ведется с использованием большого количества техники. (вестись с)
rus_verbs:конфликтовать{}, // Маша конфликтует с Петей (конфликтовать с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:иметь{}, // мне уже приходилось несколько раз иметь с ним дело.
rus_verbs:синхронизировать{}, // синхронизировать с эталонным генератором
rus_verbs:засинхронизировать{}, // засинхронизировать с эталонным генератором
rus_verbs:синхронизироваться{}, // синхронизироваться с эталонным генератором
rus_verbs:засинхронизироваться{}, // засинхронизироваться с эталонным генератором
rus_verbs:стирать{}, // стирать с мылом рубашку в тазу
rus_verbs:прыгать{}, // парашютист прыгает с парашютом
rus_verbs:выступить{}, // Он выступил с приветствием съезду.
rus_verbs:ходить{}, // В чужой монастырь со своим уставом не ходят.
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:отзываться{}, // Он отзывается об этой книге с большой похвалой.
rus_verbs:вставать{}, // он встаёт с зарёй
rus_verbs:мирить{}, // Его ум мирил всех с его дурным характером.
rus_verbs:продолжаться{}, // стрельба тем временем продолжалась с прежней точностью.
rus_verbs:договориться{}, // мы договоримся с вами
rus_verbs:побыть{}, // он хотел побыть с тобой
rus_verbs:расти{}, // Мировые производственные мощности растут с беспрецедентной скоростью
rus_verbs:вязаться{}, // вязаться с фактами
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:относиться{}, // относиться с пониманием
rus_verbs:пойти{}, // Спектакль пойдёт с участием известных артистов.
rus_verbs:бракосочетаться{}, // Потомственный кузнец бракосочетался с разорившейся графиней
rus_verbs:гулять{}, // бабушка гуляет с внуком
rus_verbs:разбираться{}, // разбираться с задачей
rus_verbs:сверить{}, // Данные были сверены с эталонными значениями
rus_verbs:делать{}, // Что делать со старым телефоном
rus_verbs:осматривать{}, // осматривать с удивлением
rus_verbs:обсудить{}, // обсудить с приятелем прохождение уровня в новой игре
rus_verbs:попрощаться{}, // попрощаться с талантливым актером
rus_verbs:задремать{}, // задремать с кружкой чая в руке
rus_verbs:связать{}, // связать катастрофу с действиями конкурентов
rus_verbs:носиться{}, // носиться с безумной идеей
rus_verbs:кончать{}, // кончать с собой
rus_verbs:обмениваться{}, // обмениваться с собеседниками
rus_verbs:переговариваться{}, // переговариваться с маяком
rus_verbs:общаться{}, // общаться с полицией
rus_verbs:завершить{}, // завершить с ошибкой
rus_verbs:обняться{}, // обняться с подругой
rus_verbs:сливаться{}, // сливаться с фоном
rus_verbs:смешаться{}, // смешаться с толпой
rus_verbs:договариваться{}, // договариваться с потерпевшим
rus_verbs:обедать{}, // обедать с гостями
rus_verbs:сообщаться{}, // сообщаться с подземной рекой
rus_verbs:сталкиваться{}, // сталкиваться со стаей птиц
rus_verbs:читаться{}, // читаться с трудом
rus_verbs:смириться{}, // смириться с утратой
rus_verbs:разделить{}, // разделить с другими ответственность
rus_verbs:роднить{}, // роднить с медведем
rus_verbs:медлить{}, // медлить с ответом
rus_verbs:скрестить{}, // скрестить с ужом
rus_verbs:покоиться{}, // покоиться с миром
rus_verbs:делиться{}, // делиться с друзьями
rus_verbs:познакомить{}, // познакомить с Олей
rus_verbs:порвать{}, // порвать с Олей
rus_verbs:завязать{}, // завязать с Олей знакомство
rus_verbs:суетиться{}, // суетиться с изданием романа
rus_verbs:соединиться{}, // соединиться с сервером
rus_verbs:справляться{}, // справляться с нуждой
rus_verbs:замешкаться{}, // замешкаться с ответом
rus_verbs:поссориться{}, // поссориться с подругой
rus_verbs:ссориться{}, // ссориться с друзьями
rus_verbs:торопить{}, // торопить с решением
rus_verbs:поздравить{}, // поздравить с победой
rus_verbs:проститься{}, // проститься с человеком
rus_verbs:поработать{}, // поработать с деревом
rus_verbs:приключиться{}, // приключиться с Колей
rus_verbs:сговориться{}, // сговориться с Ваней
rus_verbs:отъехать{}, // отъехать с ревом
rus_verbs:объединять{}, // объединять с другой кампанией
rus_verbs:употребить{}, // употребить с молоком
rus_verbs:перепутать{}, // перепутать с другой книгой
rus_verbs:запоздать{}, // запоздать с ответом
rus_verbs:подружиться{}, // подружиться с другими детьми
rus_verbs:дружить{}, // дружить с Сережей
rus_verbs:поравняться{}, // поравняться с финишной чертой
rus_verbs:ужинать{}, // ужинать с гостями
rus_verbs:расставаться{}, // расставаться с приятелями
rus_verbs:завтракать{}, // завтракать с семьей
rus_verbs:объединиться{}, // объединиться с соседями
rus_verbs:сменяться{}, // сменяться с напарником
rus_verbs:соединить{}, // соединить с сетью
rus_verbs:разговориться{}, // разговориться с охранником
rus_verbs:преподнести{}, // преподнести с помпой
rus_verbs:напечатать{}, // напечатать с картинками
rus_verbs:соединять{}, // соединять с сетью
rus_verbs:расправиться{}, // расправиться с беззащитным человеком
rus_verbs:распрощаться{}, // распрощаться с деньгами
rus_verbs:сравнить{}, // сравнить с конкурентами
rus_verbs:ознакомиться{}, // ознакомиться с выступлением
инфинитив:сочетаться{ вид:несоверш }, глагол:сочетаться{ вид:несоверш }, // сочетаться с сумочкой
деепричастие:сочетаясь{}, прилагательное:сочетающийся{}, прилагательное:сочетавшийся{},
rus_verbs:изнасиловать{}, // изнасиловать с применением чрезвычайного насилия
rus_verbs:прощаться{}, // прощаться с боевым товарищем
rus_verbs:сравнивать{}, // сравнивать с конкурентами
rus_verbs:складывать{}, // складывать с весом упаковки
rus_verbs:повестись{}, // повестись с ворами
rus_verbs:столкнуть{}, // столкнуть с отбойником
rus_verbs:переглядываться{}, // переглядываться с соседом
rus_verbs:поторопить{}, // поторопить с откликом
rus_verbs:развлекаться{}, // развлекаться с подружками
rus_verbs:заговаривать{}, // заговаривать с незнакомцами
rus_verbs:поцеловаться{}, // поцеловаться с первой девушкой
инфинитив:согласоваться{ вид:несоверш }, глагол:согласоваться{ вид:несоверш }, // согласоваться с подлежащим
деепричастие:согласуясь{}, прилагательное:согласующийся{},
rus_verbs:совпасть{}, // совпасть с оригиналом
rus_verbs:соединяться{}, // соединяться с куратором
rus_verbs:повстречаться{}, // повстречаться с героями
rus_verbs:поужинать{}, // поужинать с родителями
rus_verbs:развестись{}, // развестись с первым мужем
rus_verbs:переговорить{}, // переговорить с коллегами
rus_verbs:сцепиться{}, // сцепиться с бродячей собакой
rus_verbs:сожрать{}, // сожрать с потрохами
rus_verbs:побеседовать{}, // побеседовать со шпаной
rus_verbs:поиграть{}, // поиграть с котятами
rus_verbs:сцепить{}, // сцепить с тягачом
rus_verbs:помириться{}, // помириться с подружкой
rus_verbs:связываться{}, // связываться с бандитами
rus_verbs:совещаться{}, // совещаться с мастерами
rus_verbs:обрушиваться{}, // обрушиваться с беспощадной критикой
rus_verbs:переплестись{}, // переплестись с кустами
rus_verbs:мутить{}, // мутить с одногрупницами
rus_verbs:приглядываться{}, // приглядываться с интересом
rus_verbs:сблизиться{}, // сблизиться с врагами
rus_verbs:перешептываться{}, // перешептываться с симпатичной соседкой
rus_verbs:растереть{}, // растереть с солью
rus_verbs:смешиваться{}, // смешиваться с известью
rus_verbs:соприкоснуться{}, // соприкоснуться с тайной
rus_verbs:ладить{}, // ладить с родственниками
rus_verbs:сотрудничать{}, // сотрудничать с органами дознания
rus_verbs:съехаться{}, // съехаться с родственниками
rus_verbs:перекинуться{}, // перекинуться с коллегами парой слов
rus_verbs:советоваться{}, // советоваться с отчимом
rus_verbs:сравниться{}, // сравниться с лучшими
rus_verbs:знакомиться{}, // знакомиться с абитуриентами
rus_verbs:нырять{}, // нырять с аквалангом
rus_verbs:забавляться{}, // забавляться с куклой
rus_verbs:перекликаться{}, // перекликаться с другой статьей
rus_verbs:тренироваться{}, // тренироваться с партнершей
rus_verbs:поспорить{}, // поспорить с казночеем
инфинитив:сладить{ вид:соверш }, глагол:сладить{ вид:соверш }, // сладить с бычком
деепричастие:сладив{}, прилагательное:сладивший{ вид:соверш },
rus_verbs:примириться{}, // примириться с утратой
rus_verbs:раскланяться{}, // раскланяться с фрейлинами
rus_verbs:слечь{}, // слечь с ангиной
rus_verbs:соприкасаться{}, // соприкасаться со стеной
rus_verbs:смешать{}, // смешать с грязью
rus_verbs:пересекаться{}, // пересекаться с трассой
rus_verbs:путать{}, // путать с государственной шерстью
rus_verbs:поболтать{}, // поболтать с ученицами
rus_verbs:здороваться{}, // здороваться с профессором
rus_verbs:просчитаться{}, // просчитаться с покупкой
rus_verbs:сторожить{}, // сторожить с собакой
rus_verbs:обыскивать{}, // обыскивать с собаками
rus_verbs:переплетаться{}, // переплетаться с другой веткой
rus_verbs:обниматься{}, // обниматься с Ксюшей
rus_verbs:объединяться{}, // объединяться с конкурентами
rus_verbs:погорячиться{}, // погорячиться с покупкой
rus_verbs:мыться{}, // мыться с мылом
rus_verbs:свериться{}, // свериться с эталоном
rus_verbs:разделаться{}, // разделаться с кем-то
rus_verbs:чередоваться{}, // чередоваться с партнером
rus_verbs:налететь{}, // налететь с соратниками
rus_verbs:поспать{}, // поспать с включенным светом
rus_verbs:управиться{}, // управиться с собакой
rus_verbs:согрешить{}, // согрешить с замужней
rus_verbs:определиться{}, // определиться с победителем
rus_verbs:перемешаться{}, // перемешаться с гранулами
rus_verbs:затрудняться{}, // затрудняться с ответом
rus_verbs:обождать{}, // обождать со стартом
rus_verbs:фыркать{}, // фыркать с презрением
rus_verbs:засидеться{}, // засидеться с приятелем
rus_verbs:крепнуть{}, // крепнуть с годами
rus_verbs:пировать{}, // пировать с дружиной
rus_verbs:щебетать{}, // щебетать с сестричками
rus_verbs:маяться{}, // маяться с кашлем
rus_verbs:сближать{}, // сближать с центральным светилом
rus_verbs:меркнуть{}, // меркнуть с возрастом
rus_verbs:заспорить{}, // заспорить с оппонентами
rus_verbs:граничить{}, // граничить с Ливаном
rus_verbs:перестараться{}, // перестараться со стимуляторами
rus_verbs:объединить{}, // объединить с филиалом
rus_verbs:свыкнуться{}, // свыкнуться с утратой
rus_verbs:посоветоваться{}, // посоветоваться с адвокатами
rus_verbs:напутать{}, // напутать с ведомостями
rus_verbs:нагрянуть{}, // нагрянуть с обыском
rus_verbs:посовещаться{}, // посовещаться с судьей
rus_verbs:провернуть{}, // провернуть с друганом
rus_verbs:разделяться{}, // разделяться с сотрапезниками
rus_verbs:пересечься{}, // пересечься с второй колонной
rus_verbs:опережать{}, // опережать с большим запасом
rus_verbs:перепутаться{}, // перепутаться с другой линией
rus_verbs:соотноситься{}, // соотноситься с затратами
rus_verbs:смешивать{}, // смешивать с золой
rus_verbs:свидеться{}, // свидеться с тобой
rus_verbs:переспать{}, // переспать с графиней
rus_verbs:поладить{}, // поладить с соседями
rus_verbs:протащить{}, // протащить с собой
rus_verbs:разминуться{}, // разминуться с встречным потоком
rus_verbs:перемежаться{}, // перемежаться с успехами
rus_verbs:рассчитаться{}, // рассчитаться с кредиторами
rus_verbs:срастись{}, // срастись с телом
rus_verbs:знакомить{}, // знакомить с родителями
rus_verbs:поругаться{}, // поругаться с родителями
rus_verbs:совладать{}, // совладать с чувствами
rus_verbs:обручить{}, // обручить с богатой невестой
rus_verbs:сближаться{}, // сближаться с вражеским эсминцем
rus_verbs:замутить{}, // замутить с Ксюшей
rus_verbs:повозиться{}, // повозиться с настройкой
rus_verbs:торговаться{}, // торговаться с продавцами
rus_verbs:уединиться{}, // уединиться с девчонкой
rus_verbs:переборщить{}, // переборщить с добавкой
rus_verbs:ознакомить{}, // ознакомить с пожеланиями
rus_verbs:прочесывать{}, // прочесывать с собаками
rus_verbs:переписываться{}, // переписываться с корреспондентами
rus_verbs:повздорить{}, // повздорить с сержантом
rus_verbs:разлучить{}, // разлучить с семьей
rus_verbs:соседствовать{}, // соседствовать с цыганами
rus_verbs:застукать{}, // застукать с проститутками
rus_verbs:напуститься{}, // напуститься с кулаками
rus_verbs:сдружиться{}, // сдружиться с ребятами
rus_verbs:соперничать{}, // соперничать с параллельным классом
rus_verbs:прочесать{}, // прочесать с собаками
rus_verbs:кокетничать{}, // кокетничать с гимназистками
rus_verbs:мириться{}, // мириться с убытками
rus_verbs:оплошать{}, // оплошать с билетами
rus_verbs:отождествлять{}, // отождествлять с литературным героем
rus_verbs:хитрить{}, // хитрить с зарплатой
rus_verbs:провозиться{}, // провозиться с задачкой
rus_verbs:коротать{}, // коротать с друзьями
rus_verbs:соревноваться{}, // соревноваться с машиной
rus_verbs:уживаться{}, // уживаться с местными жителями
rus_verbs:отождествляться{}, // отождествляться с литературным героем
rus_verbs:сопоставить{}, // сопоставить с эталоном
rus_verbs:пьянствовать{}, // пьянствовать с друзьями
rus_verbs:залетать{}, // залетать с паленой водкой
rus_verbs:гастролировать{}, // гастролировать с новой цирковой программой
rus_verbs:запаздывать{}, // запаздывать с кормлением
rus_verbs:таскаться{}, // таскаться с сумками
rus_verbs:контрастировать{}, // контрастировать с туфлями
rus_verbs:сшибиться{}, // сшибиться с форвардом
rus_verbs:состязаться{}, // состязаться с лучшей командой
rus_verbs:затрудниться{}, // затрудниться с объяснением
rus_verbs:объясниться{}, // объясниться с пострадавшими
rus_verbs:разводиться{}, // разводиться со сварливой женой
rus_verbs:препираться{}, // препираться с адвокатами
rus_verbs:сосуществовать{}, // сосуществовать с крупными хищниками
rus_verbs:свестись{}, // свестись с нулевым счетом
rus_verbs:обговорить{}, // обговорить с директором
rus_verbs:обвенчаться{}, // обвенчаться с ведьмой
rus_verbs:экспериментировать{}, // экспериментировать с генами
rus_verbs:сверять{}, // сверять с таблицей
rus_verbs:сверяться{}, // свериться с таблицей
rus_verbs:сблизить{}, // сблизить с точкой
rus_verbs:гармонировать{}, // гармонировать с обоями
rus_verbs:перемешивать{}, // перемешивать с молоком
rus_verbs:трепаться{}, // трепаться с сослуживцами
rus_verbs:перемигиваться{}, // перемигиваться с соседкой
rus_verbs:разоткровенничаться{}, // разоткровенничаться с незнакомцем
rus_verbs:распить{}, // распить с собутыльниками
rus_verbs:скрестись{}, // скрестись с дикой лошадью
rus_verbs:передраться{}, // передраться с дворовыми собаками
rus_verbs:умыть{}, // умыть с мылом
rus_verbs:грызться{}, // грызться с соседями
rus_verbs:переругиваться{}, // переругиваться с соседями
rus_verbs:доиграться{}, // доиграться со спичками
rus_verbs:заладиться{}, // заладиться с подругой
rus_verbs:скрещиваться{}, // скрещиваться с дикими видами
rus_verbs:повидаться{}, // повидаться с дедушкой
rus_verbs:повоевать{}, // повоевать с орками
rus_verbs:сразиться{}, // сразиться с лучшим рыцарем
rus_verbs:кипятить{}, // кипятить с отбеливателем
rus_verbs:усердствовать{}, // усердствовать с наказанием
rus_verbs:схлестнуться{}, // схлестнуться с лучшим боксером
rus_verbs:пошептаться{}, // пошептаться с судьями
rus_verbs:сравняться{}, // сравняться с лучшими экземплярами
rus_verbs:церемониться{}, // церемониться с пьяницами
rus_verbs:консультироваться{}, // консультироваться со специалистами
rus_verbs:переусердствовать{}, // переусердствовать с наказанием
rus_verbs:проноситься{}, // проноситься с собой
rus_verbs:перемешать{}, // перемешать с гипсом
rus_verbs:темнить{}, // темнить с долгами
rus_verbs:сталкивать{}, // сталкивать с черной дырой
rus_verbs:увольнять{}, // увольнять с волчьим билетом
rus_verbs:заигрывать{}, // заигрывать с совершенно диким животным
rus_verbs:сопоставлять{}, // сопоставлять с эталонными образцами
rus_verbs:расторгнуть{}, // расторгнуть с нерасторопными поставщиками долгосрочный контракт
rus_verbs:созвониться{}, // созвониться с мамой
rus_verbs:спеться{}, // спеться с отъявленными хулиганами
rus_verbs:интриговать{}, // интриговать с придворными
rus_verbs:приобрести{}, // приобрести со скидкой
rus_verbs:задержаться{}, // задержаться со сдачей работы
rus_verbs:плавать{}, // плавать со спасательным кругом
rus_verbs:якшаться{}, // Не якшайся с врагами
инфинитив:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
инфинитив:ассоциировать{вид:несоверш},
глагол:ассоциировать{вид:соверш}, // читатели ассоциируют с собой героя книги
глагол:ассоциировать{вид:несоверш},
//+прилагательное:ассоциировавший{вид:несоверш},
прилагательное:ассоциировавший{вид:соверш},
прилагательное:ассоциирующий{},
деепричастие:ассоциируя{},
деепричастие:ассоциировав{},
rus_verbs:ассоциироваться{}, // герой книги ассоциируется с реальным персонажем
rus_verbs:аттестовывать{}, // Они аттестовывают сотрудников с помощью наборра тестов
rus_verbs:аттестовываться{}, // Сотрудники аттестовываются с помощью набора тестов
//+инфинитив:аффилировать{вид:соверш}, // эти предприятия были аффилированы с олигархом
//+глагол:аффилировать{вид:соверш},
прилагательное:аффилированный{},
rus_verbs:баловаться{}, // мальчик баловался с молотком
rus_verbs:балясничать{}, // женщина балясничала с товарками
rus_verbs:богатеть{}, // Провинция богатеет от торговли с соседями
rus_verbs:бодаться{}, // теленок бодается с деревом
rus_verbs:боксировать{}, // Майкл дважды боксировал с ним
rus_verbs:брататься{}, // Солдаты братались с бойцами союзников
rus_verbs:вальсировать{}, // Мальчик вальсирует с девочкой
rus_verbs:вверстывать{}, // Дизайнер с трудом вверстывает блоки в страницу
rus_verbs:происходить{}, // Что происходит с мировой экономикой?
rus_verbs:произойти{}, // Что произошло с экономикой?
rus_verbs:взаимодействовать{}, // Электроны взаимодействуют с фотонами
rus_verbs:вздорить{}, // Эта женщина часто вздорила с соседями
rus_verbs:сойтись{}, // Мальчик сошелся с бандой хулиганов
rus_verbs:вобрать{}, // вобрать в себя лучшие методы борьбы с вредителями
rus_verbs:водиться{}, // Няня водится с детьми
rus_verbs:воевать{}, // Фермеры воевали с волками
rus_verbs:возиться{}, // Няня возится с детьми
rus_verbs:ворковать{}, // Голубь воркует с голубкой
rus_verbs:воссоединиться{}, // Дети воссоединились с семьей
rus_verbs:воссоединяться{}, // Дети воссоединяются с семьей
rus_verbs:вошкаться{}, // Не вошкайся с этой ерундой
rus_verbs:враждовать{}, // враждовать с соседями
rus_verbs:временить{}, // временить с выходом на пенсию
rus_verbs:расстаться{}, // я не могу расстаться с тобой
rus_verbs:выдирать{}, // выдирать с мясом
rus_verbs:выдираться{}, // выдираться с мясом
rus_verbs:вытворить{}, // вытворить что-либо с чем-либо
rus_verbs:вытворять{}, // вытворять что-либо с чем-либо
rus_verbs:сделать{}, // сделать с чем-то
rus_verbs:домыть{}, // домыть с мылом
rus_verbs:случиться{}, // случиться с кем-то
rus_verbs:остаться{}, // остаться с кем-то
rus_verbs:случать{}, // случать с породистым кобельком
rus_verbs:послать{}, // послать с весточкой
rus_verbs:работать{}, // работать с роботами
rus_verbs:провести{}, // провести с девчонками время
rus_verbs:заговорить{}, // заговорить с незнакомкой
rus_verbs:прошептать{}, // прошептать с придыханием
rus_verbs:читать{}, // читать с выражением
rus_verbs:слушать{}, // слушать с повышенным вниманием
rus_verbs:принести{}, // принести с собой
rus_verbs:спать{}, // спать с женщинами
rus_verbs:закончить{}, // закончить с приготовлениями
rus_verbs:помочь{}, // помочь с перестановкой
rus_verbs:уехать{}, // уехать с семьей
rus_verbs:случаться{}, // случаться с кем-то
rus_verbs:кутить{}, // кутить с проститутками
rus_verbs:разговаривать{}, // разговаривать с ребенком
rus_verbs:погодить{}, // погодить с ликвидацией
rus_verbs:считаться{}, // считаться с чужим мнением
rus_verbs:носить{}, // носить с собой
rus_verbs:хорошеть{}, // хорошеть с каждым днем
rus_verbs:приводить{}, // приводить с собой
rus_verbs:прыгнуть{}, // прыгнуть с парашютом
rus_verbs:петь{}, // петь с чувством
rus_verbs:сложить{}, // сложить с результатом
rus_verbs:познакомиться{}, // познакомиться с другими студентами
rus_verbs:обращаться{}, // обращаться с животными
rus_verbs:съесть{}, // съесть с хлебом
rus_verbs:ошибаться{}, // ошибаться с дозировкой
rus_verbs:столкнуться{}, // столкнуться с медведем
rus_verbs:справиться{}, // справиться с нуждой
rus_verbs:торопиться{}, // торопиться с ответом
rus_verbs:поздравлять{}, // поздравлять с победой
rus_verbs:объясняться{}, // объясняться с начальством
rus_verbs:пошутить{}, // пошутить с подругой
rus_verbs:поздороваться{}, // поздороваться с коллегами
rus_verbs:поступать{}, // Как поступать с таким поведением?
rus_verbs:определяться{}, // определяться с кандидатами
rus_verbs:связаться{}, // связаться с поставщиком
rus_verbs:спорить{}, // спорить с собеседником
rus_verbs:разобраться{}, // разобраться с делами
rus_verbs:ловить{}, // ловить с удочкой
rus_verbs:помедлить{}, // Кандидат помедлил с ответом на заданный вопрос
rus_verbs:шутить{}, // шутить с диким зверем
rus_verbs:разорвать{}, // разорвать с поставщиком контракт
rus_verbs:увезти{}, // увезти с собой
rus_verbs:унести{}, // унести с собой
rus_verbs:сотворить{}, // сотворить с собой что-то нехорошее
rus_verbs:складываться{}, // складываться с первым импульсом
rus_verbs:соглашаться{}, // соглашаться с предложенным договором
//rus_verbs:покончить{}, // покончить с развратом
rus_verbs:прихватить{}, // прихватить с собой
rus_verbs:похоронить{}, // похоронить с почестями
rus_verbs:связывать{}, // связывать с компанией свою судьбу
rus_verbs:совпадать{}, // совпадать с предсказанием
rus_verbs:танцевать{}, // танцевать с девушками
rus_verbs:поделиться{}, // поделиться с выжившими
rus_verbs:оставаться{}, // я не хотел оставаться с ним в одной комнате.
rus_verbs:беседовать{}, // преподаватель, беседующий со студентами
rus_verbs:бороться{}, // человек, борющийся со смертельной болезнью
rus_verbs:шептаться{}, // девочка, шепчущаяся с подругой
rus_verbs:сплетничать{}, // женщина, сплетничавшая с товарками
rus_verbs:поговорить{}, // поговорить с виновниками
rus_verbs:сказать{}, // сказать с трудом
rus_verbs:произнести{}, // произнести с трудом
rus_verbs:говорить{}, // говорить с акцентом
rus_verbs:произносить{}, // произносить с трудом
rus_verbs:встречаться{}, // кто с Антонио встречался?
rus_verbs:посидеть{}, // посидеть с друзьями
rus_verbs:расквитаться{}, // расквитаться с обидчиком
rus_verbs:поквитаться{}, // поквитаться с обидчиком
rus_verbs:ругаться{}, // ругаться с женой
rus_verbs:поскандалить{}, // поскандалить с женой
rus_verbs:потанцевать{}, // потанцевать с подругой
rus_verbs:скандалить{}, // скандалить с соседями
rus_verbs:разругаться{}, // разругаться с другом
rus_verbs:болтать{}, // болтать с подругами
rus_verbs:потрепаться{}, // потрепаться с соседкой
rus_verbs:войти{}, // войти с регистрацией
rus_verbs:входить{}, // входить с регистрацией
rus_verbs:возвращаться{}, // возвращаться с триумфом
rus_verbs:опоздать{}, // Он опоздал с подачей сочинения.
rus_verbs:молчать{}, // Он молчал с ледяным спокойствием.
rus_verbs:сражаться{}, // Он героически сражался с врагами.
rus_verbs:выходить{}, // Он всегда выходит с зонтиком.
rus_verbs:сличать{}, // сличать перевод с оригиналом
rus_verbs:начать{}, // я начал с товарищем спор о религии
rus_verbs:согласовать{}, // Маша согласовала с Петей дальнейшие поездки
rus_verbs:приходить{}, // Приходите с нею.
rus_verbs:жить{}, // кто с тобой жил?
rus_verbs:расходиться{}, // Маша расходится с Петей
rus_verbs:сцеплять{}, // сцеплять карабин с обвязкой
rus_verbs:торговать{}, // мы торгуем с ними нефтью
rus_verbs:уединяться{}, // уединяться с подругой в доме
rus_verbs:уладить{}, // уладить конфликт с соседями
rus_verbs:идти{}, // Я шел туда с тяжёлым сердцем.
rus_verbs:разделять{}, // Я разделяю с вами горе и радость.
rus_verbs:обратиться{}, // Я обратился к нему с просьбой о помощи.
rus_verbs:захватить{}, // Я не захватил с собой денег.
прилагательное:знакомый{}, // Я знаком с ними обоими.
rus_verbs:вести{}, // Я веду с ней переписку.
прилагательное:сопряженный{}, // Это сопряжено с большими трудностями.
прилагательное:связанный{причастие}, // Это дело связано с риском.
rus_verbs:поехать{}, // Хотите поехать со мной в театр?
rus_verbs:проснуться{}, // Утром я проснулся с ясной головой.
rus_verbs:лететь{}, // Самолёт летел со скоростью звука.
rus_verbs:играть{}, // С огнём играть опасно!
rus_verbs:поделать{}, // С ним ничего не поделаешь.
rus_verbs:стрястись{}, // С ней стряслось несчастье.
rus_verbs:смотреться{}, // Пьеса смотрится с удовольствием.
rus_verbs:смотреть{}, // Она смотрела на меня с явным неудовольствием.
rus_verbs:разойтись{}, // Она разошлась с мужем.
rus_verbs:пристать{}, // Она пристала ко мне с расспросами.
rus_verbs:посмотреть{}, // Она посмотрела на меня с удивлением.
rus_verbs:поступить{}, // Она плохо поступила с ним.
rus_verbs:выйти{}, // Она вышла с усталым и недовольным видом.
rus_verbs:взять{}, // Возьмите с собой только самое необходимое.
rus_verbs:наплакаться{}, // Наплачется она с ним.
rus_verbs:лежать{}, // Он лежит с воспалением лёгких.
rus_verbs:дышать{}, // дышащий с трудом
rus_verbs:брать{}, // брать с собой
rus_verbs:мчаться{}, // Автомобиль мчится с необычайной быстротой.
rus_verbs:упасть{}, // Ваза упала со звоном.
rus_verbs:вернуться{}, // мы вернулись вчера домой с полным лукошком
rus_verbs:сидеть{}, // Она сидит дома с ребенком
rus_verbs:встретиться{}, // встречаться с кем-либо
ГЛ_ИНФ(придти), прилагательное:пришедший{}, // пришедший с другом
ГЛ_ИНФ(постирать), прилагательное:постиранный{}, деепричастие:постирав{},
rus_verbs:мыть{}
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Твор предлог:с{} *:*{падеж:твор} }
then return true
}
#endregion ТВОРИТЕЛЬНЫЙ
#region РОДИТЕЛЬНЫЙ
wordentry_set Гл_С_Род=
{
rus_verbs:УХОДИТЬ{}, // Но с базы не уходить.
rus_verbs:РВАНУТЬ{}, // Водитель прорычал проклятие и рванул машину с места. (РВАНУТЬ)
rus_verbs:ОХВАТИТЬ{}, // огонь охватил его со всех сторон (ОХВАТИТЬ)
rus_verbs:ЗАМЕТИТЬ{}, // Он понимал, что свет из тайника невозможно заметить с палубы (ЗАМЕТИТЬ/РАЗГЛЯДЕТЬ)
rus_verbs:РАЗГЛЯДЕТЬ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Птицы размером с орлицу, вероятно, не могли бы подняться в воздух, не спланировав с высокого утеса. (СПЛАНИРОВАТЬ)
rus_verbs:УМЕРЕТЬ{}, // Он умрет с голоду. (УМЕРЕТЬ)
rus_verbs:ВСПУГНУТЬ{}, // Оба упали с лязгом, вспугнувшим птиц с ближайших деревьев (ВСПУГНУТЬ)
rus_verbs:РЕВЕТЬ{}, // Время от времени какой-то ящер ревел с берега или самой реки. (РЕВЕТЬ/ЗАРЕВЕТЬ/ПРОРЕВЕТЬ/ЗАОРАТЬ/ПРООРАТЬ/ОРАТЬ/ПРОКРИЧАТЬ/ЗАКРИЧАТЬ/ВОПИТЬ/ЗАВОПИТЬ)
rus_verbs:ЗАРЕВЕТЬ{}, //
rus_verbs:ПРОРЕВЕТЬ{}, //
rus_verbs:ЗАОРАТЬ{}, //
rus_verbs:ПРООРАТЬ{}, //
rus_verbs:ОРАТЬ{}, //
rus_verbs:ЗАКРИЧАТЬ{},
rus_verbs:ВОПИТЬ{}, //
rus_verbs:ЗАВОПИТЬ{}, //
rus_verbs:СТАЩИТЬ{}, // Я видела как они стащили его с валуна и увели с собой. (СТАЩИТЬ/СТАСКИВАТЬ)
rus_verbs:СТАСКИВАТЬ{}, //
rus_verbs:ПРОВЫТЬ{}, // Призрак трубного зова провыл с другой стороны дверей. (ПРОВЫТЬ, ЗАВЫТЬ, ВЫТЬ)
rus_verbs:ЗАВЫТЬ{}, //
rus_verbs:ВЫТЬ{}, //
rus_verbs:СВЕТИТЬ{}, // Полуденное майское солнце ярко светило с голубых небес Аризоны. (СВЕТИТЬ)
rus_verbs:ОТСВЕЧИВАТЬ{}, // Солнце отсвечивало с белых лошадей, белых щитов и белых перьев и искрилось на наконечниках пик. (ОТСВЕЧИВАТЬ С, ИСКРИТЬСЯ НА)
rus_verbs:перегнать{}, // Скот нужно перегнать с этого пастбища на другое
rus_verbs:собирать{}, // мальчики начали собирать со столов посуду
rus_verbs:разглядывать{}, // ты ее со всех сторон разглядывал
rus_verbs:СЖИМАТЬ{}, // меня плотно сжимали со всех сторон (СЖИМАТЬ)
rus_verbs:СОБРАТЬСЯ{}, // со всего света собрались! (СОБРАТЬСЯ)
rus_verbs:ИЗГОНЯТЬ{}, // Вино в пакетах изгоняют с рынка (ИЗГОНЯТЬ)
rus_verbs:ВЛЮБИТЬСЯ{}, // влюбился в нее с первого взгляда (ВЛЮБИТЬСЯ)
rus_verbs:РАЗДАВАТЬСЯ{}, // теперь крик раздавался со всех сторон (РАЗДАВАТЬСЯ)
rus_verbs:ПОСМОТРЕТЬ{}, // Посмотрите на это с моей точки зрения (ПОСМОТРЕТЬ С род)
rus_verbs:СХОДИТЬ{}, // принимать участие во всех этих событиях - значит продолжать сходить с ума (СХОДИТЬ С род)
rus_verbs:РУХНУТЬ{}, // В Башкирии микроавтобус рухнул с моста (РУХНУТЬ С)
rus_verbs:УВОЛИТЬ{}, // рекомендовать уволить их с работы (УВОЛИТЬ С)
rus_verbs:КУПИТЬ{}, // еда , купленная с рук (КУПИТЬ С род)
rus_verbs:УБРАТЬ{}, // помочь убрать со стола? (УБРАТЬ С)
rus_verbs:ТЯНУТЬ{}, // с моря тянуло ветром (ТЯНУТЬ С)
rus_verbs:ПРИХОДИТЬ{}, // приходит с работы муж (ПРИХОДИТЬ С)
rus_verbs:ПРОПАСТЬ{}, // изображение пропало с экрана (ПРОПАСТЬ С)
rus_verbs:ПОТЯНУТЬ{}, // с балкона потянуло холодом (ПОТЯНУТЬ С род)
rus_verbs:РАЗДАТЬСЯ{}, // с палубы раздался свист (РАЗДАТЬСЯ С род)
rus_verbs:ЗАЙТИ{}, // зашел с другой стороны (ЗАЙТИ С род)
rus_verbs:НАЧАТЬ{}, // давай начнем с этого (НАЧАТЬ С род)
rus_verbs:УВЕСТИ{}, // дала увести с развалин (УВЕСТИ С род)
rus_verbs:ОПУСКАТЬСЯ{}, // с гор опускалась ночь (ОПУСКАТЬСЯ С)
rus_verbs:ВСКОЧИТЬ{}, // Тристан вскочил с места (ВСКОЧИТЬ С род)
rus_verbs:БРАТЬ{}, // беру с него пример (БРАТЬ С род)
rus_verbs:ПРИПОДНЯТЬСЯ{}, // голова приподнялась с плеча (ПРИПОДНЯТЬСЯ С род)
rus_verbs:ПОЯВИТЬСЯ{}, // всадники появились с востока (ПОЯВИТЬСЯ С род)
rus_verbs:НАЛЕТЕТЬ{}, // с моря налетел ветер (НАЛЕТЕТЬ С род)
rus_verbs:ВЗВИТЬСЯ{}, // Натан взвился с места (ВЗВИТЬСЯ С род)
rus_verbs:ПОДОБРАТЬ{}, // подобрал с земли копье (ПОДОБРАТЬ С)
rus_verbs:ДЕРНУТЬСЯ{}, // Кирилл дернулся с места (ДЕРНУТЬСЯ С род)
rus_verbs:ВОЗВРАЩАТЬСЯ{}, // они возвращались с реки (ВОЗВРАЩАТЬСЯ С род)
rus_verbs:ПЛЫТЬ{}, // плыли они с запада (ПЛЫТЬ С род)
rus_verbs:ЗНАТЬ{}, // одно знали с древности (ЗНАТЬ С)
rus_verbs:НАКЛОНИТЬСЯ{}, // всадник наклонился с лошади (НАКЛОНИТЬСЯ С)
rus_verbs:НАЧАТЬСЯ{}, // началось все со скуки (НАЧАТЬСЯ С)
прилагательное:ИЗВЕСТНЫЙ{}, // Культура его известна со времен глубокой древности (ИЗВЕСТНЫЙ С)
rus_verbs:СБИТЬ{}, // Порыв ветра сбил Ваньку с ног (ts СБИТЬ С)
rus_verbs:СОБИРАТЬСЯ{}, // они собираются сюда со всей равнины. (СОБИРАТЬСЯ С род)
rus_verbs:смыть{}, // Дождь должен смыть с листьев всю пыль. (СМЫТЬ С)
rus_verbs:привстать{}, // Мартин привстал со своего стула. (привстать с)
rus_verbs:спасть{}, // тяжесть спала с души. (спасть с)
rus_verbs:выглядеть{}, // так оно со стороны выглядело. (ВЫГЛЯДЕТЬ С)
rus_verbs:повернуть{}, // к вечеру они повернули с нее направо. (ПОВЕРНУТЬ С)
rus_verbs:ТЯНУТЬСЯ{}, // со стороны реки ко мне тянулись языки тумана. (ТЯНУТЬСЯ С)
rus_verbs:ВОЕВАТЬ{}, // Генерал воевал с юных лет. (ВОЕВАТЬ С чего-то)
rus_verbs:БОЛЕТЬ{}, // Голова болит с похмелья. (БОЛЕТЬ С)
rus_verbs:приближаться{}, // со стороны острова приближалась лодка.
rus_verbs:ПОТЯНУТЬСЯ{}, // со всех сторон к нему потянулись руки. (ПОТЯНУТЬСЯ С)
rus_verbs:пойти{}, // низкий гул пошел со стороны долины. (пошел с)
rus_verbs:зашевелиться{}, // со всех сторон зашевелились кусты. (зашевелиться с)
rus_verbs:МЧАТЬСЯ{}, // со стороны леса мчались всадники. (МЧАТЬСЯ С)
rus_verbs:БЕЖАТЬ{}, // люди бежали со всех ног. (БЕЖАТЬ С)
rus_verbs:СЛЫШАТЬСЯ{}, // шум слышался со стороны моря. (СЛЫШАТЬСЯ С)
rus_verbs:ЛЕТЕТЬ{}, // со стороны деревни летела птица. (ЛЕТЕТЬ С)
rus_verbs:ПЕРЕТЬ{}, // враги прут со всех сторон. (ПЕРЕТЬ С)
rus_verbs:ПОСЫПАТЬСЯ{}, // вопросы посыпались со всех сторон. (ПОСЫПАТЬСЯ С)
rus_verbs:ИДТИ{}, // угроза шла со стороны моря. (ИДТИ С + род.п.)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // со стен послышались крики ужаса. (ПОСЛЫШАТЬСЯ С)
rus_verbs:ОБРУШИТЬСЯ{}, // звуки обрушились со всех сторон. (ОБРУШИТЬСЯ С)
rus_verbs:УДАРИТЬ{}, // голоса ударили со всех сторон. (УДАРИТЬ С)
rus_verbs:ПОКАЗАТЬСЯ{}, // со стороны деревни показались земляне. (ПОКАЗАТЬСЯ С)
rus_verbs:прыгать{}, // придется прыгать со второго этажа. (прыгать с)
rus_verbs:СТОЯТЬ{}, // со всех сторон стоял лес. (СТОЯТЬ С)
rus_verbs:доноситься{}, // шум со двора доносился чудовищный. (доноситься с)
rus_verbs:мешать{}, // мешать воду с мукой (мешать с)
rus_verbs:вестись{}, // Переговоры ведутся с позиции силы. (вестись с)
rus_verbs:вставать{}, // Он не встает с кровати. (вставать с)
rus_verbs:окружать{}, // зеленые щупальца окружали ее со всех сторон. (окружать с)
rus_verbs:причитаться{}, // С вас причитается 50 рублей.
rus_verbs:соскользнуть{}, // его острый клюв соскользнул с ее руки.
rus_verbs:сократить{}, // Его сократили со службы.
rus_verbs:поднять{}, // рука подняла с пола
rus_verbs:поднимать{},
rus_verbs:тащить{}, // тем временем другие пришельцы тащили со всех сторон камни.
rus_verbs:полететь{}, // Мальчик полетел с лестницы.
rus_verbs:литься{}, // вода льется с неба
rus_verbs:натечь{}, // натечь с сапог
rus_verbs:спрыгивать{}, // спрыгивать с движущегося трамвая
rus_verbs:съезжать{}, // съезжать с заявленной темы
rus_verbs:покатываться{}, // покатываться со смеху
rus_verbs:перескакивать{}, // перескакивать с одного примера на другой
rus_verbs:сдирать{}, // сдирать с тела кожу
rus_verbs:соскальзывать{}, // соскальзывать с крючка
rus_verbs:сметать{}, // сметать с прилавков
rus_verbs:кувыркнуться{}, // кувыркнуться со ступеньки
rus_verbs:прокаркать{}, // прокаркать с ветки
rus_verbs:стряхивать{}, // стряхивать с одежды
rus_verbs:сваливаться{}, // сваливаться с лестницы
rus_verbs:слизнуть{}, // слизнуть с лица
rus_verbs:доставляться{}, // доставляться с фермы
rus_verbs:обступать{}, // обступать с двух сторон
rus_verbs:повскакивать{}, // повскакивать с мест
rus_verbs:обозревать{}, // обозревать с вершины
rus_verbs:слинять{}, // слинять с урока
rus_verbs:смывать{}, // смывать с лица
rus_verbs:спихнуть{}, // спихнуть со стола
rus_verbs:обозреть{}, // обозреть с вершины
rus_verbs:накупить{}, // накупить с рук
rus_verbs:схлынуть{}, // схлынуть с берега
rus_verbs:спикировать{}, // спикировать с километровой высоты
rus_verbs:уползти{}, // уползти с поля боя
rus_verbs:сбиваться{}, // сбиваться с пути
rus_verbs:отлучиться{}, // отлучиться с поста
rus_verbs:сигануть{}, // сигануть с крыши
rus_verbs:сместить{}, // сместить с поста
rus_verbs:списать{}, // списать с оригинального устройства
инфинитив:слетать{ вид:несоверш }, глагол:слетать{ вид:несоверш }, // слетать с трассы
деепричастие:слетая{},
rus_verbs:напиваться{}, // напиваться с горя
rus_verbs:свесить{}, // свесить с крыши
rus_verbs:заполучить{}, // заполучить со склада
rus_verbs:спадать{}, // спадать с глаз
rus_verbs:стартовать{}, // стартовать с мыса
rus_verbs:спереть{}, // спереть со склада
rus_verbs:согнать{}, // согнать с живота
rus_verbs:скатываться{}, // скатываться со стога
rus_verbs:сняться{}, // сняться с выборов
rus_verbs:слезать{}, // слезать со стола
rus_verbs:деваться{}, // деваться с подводной лодки
rus_verbs:огласить{}, // огласить с трибуны
rus_verbs:красть{}, // красть со склада
rus_verbs:расширить{}, // расширить с торца
rus_verbs:угадывать{}, // угадывать с полуслова
rus_verbs:оскорбить{}, // оскорбить со сцены
rus_verbs:срывать{}, // срывать с головы
rus_verbs:сшибить{}, // сшибить с коня
rus_verbs:сбивать{}, // сбивать с одежды
rus_verbs:содрать{}, // содрать с посетителей
rus_verbs:столкнуть{}, // столкнуть с горы
rus_verbs:отряхнуть{}, // отряхнуть с одежды
rus_verbs:сбрасывать{}, // сбрасывать с борта
rus_verbs:расстреливать{}, // расстреливать с борта вертолета
rus_verbs:придти{}, // мать скоро придет с работы
rus_verbs:съехать{}, // Миша съехал с горки
rus_verbs:свисать{}, // свисать с веток
rus_verbs:стянуть{}, // стянуть с кровати
rus_verbs:скинуть{}, // скинуть снег с плеча
rus_verbs:загреметь{}, // загреметь со стула
rus_verbs:сыпаться{}, // сыпаться с неба
rus_verbs:стряхнуть{}, // стряхнуть с головы
rus_verbs:сползти{}, // сползти со стула
rus_verbs:стереть{}, // стереть с экрана
rus_verbs:прогнать{}, // прогнать с фермы
rus_verbs:смахнуть{}, // смахнуть со стола
rus_verbs:спускать{}, // спускать с поводка
rus_verbs:деться{}, // деться с подводной лодки
rus_verbs:сдернуть{}, // сдернуть с себя
rus_verbs:сдвинуться{}, // сдвинуться с места
rus_verbs:слететь{}, // слететь с катушек
rus_verbs:обступить{}, // обступить со всех сторон
rus_verbs:снести{}, // снести с плеч
инфинитив:сбегать{ вид:несоверш }, глагол:сбегать{ вид:несоверш }, // сбегать с уроков
деепричастие:сбегая{}, прилагательное:сбегающий{},
// прилагательное:сбегавший{ вид:несоверш },
rus_verbs:запить{}, // запить с горя
rus_verbs:рубануть{}, // рубануть с плеча
rus_verbs:чертыхнуться{}, // чертыхнуться с досады
rus_verbs:срываться{}, // срываться с цепи
rus_verbs:смыться{}, // смыться с уроков
rus_verbs:похитить{}, // похитить со склада
rus_verbs:смести{}, // смести со своего пути
rus_verbs:отгружать{}, // отгружать со склада
rus_verbs:отгрузить{}, // отгрузить со склада
rus_verbs:бросаться{}, // Дети бросались в воду с моста
rus_verbs:броситься{}, // самоубийца бросился с моста в воду
rus_verbs:взимать{}, // Билетер взимает плату с каждого посетителя
rus_verbs:взиматься{}, // Плата взимается с любого посетителя
rus_verbs:взыскать{}, // Приставы взыскали долг с бедолаги
rus_verbs:взыскивать{}, // Приставы взыскивают с бедолаги все долги
rus_verbs:взыскиваться{}, // Долги взыскиваются с алиментщиков
rus_verbs:вспархивать{}, // вспархивать с цветка
rus_verbs:вспорхнуть{}, // вспорхнуть с ветки
rus_verbs:выбросить{}, // выбросить что-то с балкона
rus_verbs:выводить{}, // выводить с одежды пятна
rus_verbs:снять{}, // снять с головы
rus_verbs:начинать{}, // начинать с эскиза
rus_verbs:двинуться{}, // двинуться с места
rus_verbs:начинаться{}, // начинаться с гардероба
rus_verbs:стечь{}, // стечь с крыши
rus_verbs:слезть{}, // слезть с кучи
rus_verbs:спуститься{}, // спуститься с крыши
rus_verbs:сойти{}, // сойти с пьедестала
rus_verbs:свернуть{}, // свернуть с пути
rus_verbs:сорвать{}, // сорвать с цепи
rus_verbs:сорваться{}, // сорваться с поводка
rus_verbs:тронуться{}, // тронуться с места
rus_verbs:угадать{}, // угадать с первой попытки
rus_verbs:спустить{}, // спустить с лестницы
rus_verbs:соскочить{}, // соскочить с крючка
rus_verbs:сдвинуть{}, // сдвинуть с места
rus_verbs:подниматься{}, // туман, поднимающийся с болота
rus_verbs:подняться{}, // туман, поднявшийся с болота
rus_verbs:валить{}, // Резкий порывистый ветер валит прохожих с ног.
rus_verbs:свалить{}, // Резкий порывистый ветер свалит тебя с ног.
rus_verbs:донестись{}, // С улицы донесся шум дождя.
rus_verbs:опасть{}, // Опавшие с дерева листья.
rus_verbs:махнуть{}, // Он махнул с берега в воду.
rus_verbs:исчезнуть{}, // исчезнуть с экрана
rus_verbs:свалиться{}, // свалиться со сцены
rus_verbs:упасть{}, // упасть с дерева
rus_verbs:вернуться{}, // Он ещё не вернулся с работы.
rus_verbs:сдувать{}, // сдувать пух с одуванчиков
rus_verbs:свергать{}, // свергать царя с трона
rus_verbs:сбиться{}, // сбиться с пути
rus_verbs:стирать{}, // стирать тряпкой надпись с доски
rus_verbs:убирать{}, // убирать мусор c пола
rus_verbs:удалять{}, // удалять игрока с поля
rus_verbs:окружить{}, // Япония окружена со всех сторон морями.
rus_verbs:снимать{}, // Я снимаю с себя всякую ответственность за его поведение.
глагол:писаться{ aux stress="пис^аться" }, // Собственные имена пишутся с большой буквы.
прилагательное:спокойный{}, // С этой стороны я спокоен.
rus_verbs:спросить{}, // С тебя за всё спросят.
rus_verbs:течь{}, // С него течёт пот.
rus_verbs:дуть{}, // С моря дует ветер.
rus_verbs:капать{}, // С его лица капали крупные капли пота.
rus_verbs:опустить{}, // Она опустила ребёнка с рук на пол.
rus_verbs:спрыгнуть{}, // Она легко спрыгнула с коня.
rus_verbs:встать{}, // Все встали со стульев.
rus_verbs:сбросить{}, // Войдя в комнату, он сбросил с себя пальто.
rus_verbs:взять{}, // Возьми книгу с полки.
rus_verbs:спускаться{}, // Мы спускались с горы.
rus_verbs:уйти{}, // Он нашёл себе заместителя и ушёл со службы.
rus_verbs:порхать{}, // Бабочка порхает с цветка на цветок.
rus_verbs:отправляться{}, // Ваш поезд отправляется со второй платформы.
rus_verbs:двигаться{}, // Он не двигался с места.
rus_verbs:отходить{}, // мой поезд отходит с первого пути
rus_verbs:попасть{}, // Майкл попал в кольцо с десятиметровой дистанции
rus_verbs:падать{}, // снег падает с ветвей
rus_verbs:скрыться{} // Ее водитель, бросив машину, скрылся с места происшествия.
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:род} }
then return true
}
fact гл_предл
{
if context { Гл_С_Род предлог:с{} *:*{падеж:парт} }
then return true
}
#endregion РОДИТЕЛЬНЫЙ
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:твор } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:с{} *:*{ падеж:род } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:с{} * }
then return false,-5
}
#endregion Предлог_С
/*
#region Предлог_ПОД
// -------------- ПРЕДЛОГ 'ПОД' -----------------------
fact гл_предл
{
if context { * предлог:под{} @regex("[a-z]+[0-9]*") }
then return true
}
// ПОД+вин.п. не может присоединяться к существительным, поэтому
// он присоединяется к любым глаголам.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:вин } }
then return true
}
wordentry_set Гл_ПОД_твор=
{
rus_verbs:извиваться{}, // извивалась под его длинными усами
rus_verbs:РАСПРОСТРАНЯТЬСЯ{}, // Под густым ковром травы и плотным сплетением корней (РАСПРОСТРАНЯТЬСЯ)
rus_verbs:БРОСИТЬ{}, // чтобы ты его под деревом бросил? (БРОСИТЬ)
rus_verbs:БИТЬСЯ{}, // под моей щекой сильно билось его сердце (БИТЬСЯ)
rus_verbs:ОПУСТИТЬСЯ{}, // глаза его опустились под ее желтым взглядом (ОПУСТИТЬСЯ)
rus_verbs:ВЗДЫМАТЬСЯ{}, // его грудь судорожно вздымалась под ее рукой (ВЗДЫМАТЬСЯ)
rus_verbs:ПРОМЧАТЬСЯ{}, // Она промчалась под ними и исчезла за изгибом горы. (ПРОМЧАТЬСЯ)
rus_verbs:всплыть{}, // Наконец он всплыл под нависавшей кормой, так и не отыскав того, что хотел. (всплыть)
rus_verbs:КОНЧАТЬСЯ{}, // Он почти вертикально уходит в реку и кончается глубоко под водой. (КОНЧАТЬСЯ)
rus_verbs:ПОЛЗТИ{}, // Там они ползли под спутанным терновником и сквозь переплетавшиеся кусты (ПОЛЗТИ)
rus_verbs:ПРОХОДИТЬ{}, // Вольф проходил под гигантскими ветвями деревьев и мхов, свисавших с ветвей зелеными водопадами. (ПРОХОДИТЬ, ПРОПОЛЗТИ, ПРОПОЛЗАТЬ)
rus_verbs:ПРОПОЛЗТИ{}, //
rus_verbs:ПРОПОЛЗАТЬ{}, //
rus_verbs:ИМЕТЬ{}, // Эти предположения не имеют под собой никакой почвы (ИМЕТЬ)
rus_verbs:НОСИТЬ{}, // она носит под сердцем ребенка (НОСИТЬ)
rus_verbs:ПАСТЬ{}, // Рим пал под натиском варваров (ПАСТЬ)
rus_verbs:УТОНУТЬ{}, // Выступавшие старческие вены снова утонули под гладкой твердой плотью. (УТОНУТЬ)
rus_verbs:ВАЛЯТЬСЯ{}, // Под его кривыми серыми ветвями и пестрыми коричнево-зелеными листьями валялись пустые ореховые скорлупки и сердцевины плодов. (ВАЛЯТЬСЯ)
rus_verbs:вздрогнуть{}, // она вздрогнула под его взглядом
rus_verbs:иметься{}, // у каждого под рукой имелся арбалет
rus_verbs:ЖДАТЬ{}, // Сашка уже ждал под дождем (ЖДАТЬ)
rus_verbs:НОЧЕВАТЬ{}, // мне приходилось ночевать под открытым небом (НОЧЕВАТЬ)
rus_verbs:УЗНАТЬ{}, // вы должны узнать меня под этим именем (УЗНАТЬ)
rus_verbs:ЗАДЕРЖИВАТЬСЯ{}, // мне нельзя задерживаться под землей! (ЗАДЕРЖИВАТЬСЯ)
rus_verbs:ПОГИБНУТЬ{}, // под их копытами погибли целые армии! (ПОГИБНУТЬ)
rus_verbs:РАЗДАВАТЬСЯ{}, // под ногами у меня раздавался сухой хруст (РАЗДАВАТЬСЯ)
rus_verbs:КРУЖИТЬСЯ{}, // поверхность планеты кружилась у него под ногами (КРУЖИТЬСЯ)
rus_verbs:ВИСЕТЬ{}, // под глазами у него висели тяжелые складки кожи (ВИСЕТЬ)
rus_verbs:содрогнуться{}, // содрогнулся под ногами каменный пол (СОДРОГНУТЬСЯ)
rus_verbs:СОБИРАТЬСЯ{}, // темнота уже собиралась под деревьями (СОБИРАТЬСЯ)
rus_verbs:УПАСТЬ{}, // толстяк упал под градом ударов (УПАСТЬ)
rus_verbs:ДВИНУТЬСЯ{}, // лодка двинулась под водой (ДВИНУТЬСЯ)
rus_verbs:ЦАРИТЬ{}, // под его крышей царила холодная зима (ЦАРИТЬ)
rus_verbs:ПРОВАЛИТЬСЯ{}, // под копытами его лошади провалился мост (ПРОВАЛИТЬСЯ ПОД твор)
rus_verbs:ЗАДРОЖАТЬ{}, // земля задрожала под ногами (ЗАДРОЖАТЬ)
rus_verbs:НАХМУРИТЬСЯ{}, // государь нахмурился под маской (НАХМУРИТЬСЯ)
rus_verbs:РАБОТАТЬ{}, // работать под угрозой нельзя (РАБОТАТЬ)
rus_verbs:ШЕВЕЛЬНУТЬСЯ{}, // под ногой шевельнулся камень (ШЕВЕЛЬНУТЬСЯ)
rus_verbs:ВИДЕТЬ{}, // видел тебя под камнем. (ВИДЕТЬ)
rus_verbs:ОСТАТЬСЯ{}, // второе осталось под водой (ОСТАТЬСЯ)
rus_verbs:КИПЕТЬ{}, // вода кипела под копытами (КИПЕТЬ)
rus_verbs:СИДЕТЬ{}, // может сидит под деревом (СИДЕТЬ)
rus_verbs:МЕЛЬКНУТЬ{}, // под нами мелькнуло море (МЕЛЬКНУТЬ)
rus_verbs:ПОСЛЫШАТЬСЯ{}, // под окном послышался шум (ПОСЛЫШАТЬСЯ)
rus_verbs:ТЯНУТЬСЯ{}, // под нами тянулись облака (ТЯНУТЬСЯ)
rus_verbs:ДРОЖАТЬ{}, // земля дрожала под ним (ДРОЖАТЬ)
rus_verbs:ПРИЙТИСЬ{}, // хуже пришлось под землей (ПРИЙТИСЬ)
rus_verbs:ГОРЕТЬ{}, // лампа горела под потолком (ГОРЕТЬ)
rus_verbs:ПОЛОЖИТЬ{}, // положил под деревом плащ (ПОЛОЖИТЬ)
rus_verbs:ЗАГОРЕТЬСЯ{}, // под деревьями загорелся костер (ЗАГОРЕТЬСЯ)
rus_verbs:ПРОНОСИТЬСЯ{}, // под нами проносились крыши (ПРОНОСИТЬСЯ)
rus_verbs:ПОТЯНУТЬСЯ{}, // под кораблем потянулись горы (ПОТЯНУТЬСЯ)
rus_verbs:БЕЖАТЬ{}, // беги под серой стеной ночи (БЕЖАТЬ)
rus_verbs:РАЗДАТЬСЯ{}, // под окном раздалось тяжелое дыхание (РАЗДАТЬСЯ)
rus_verbs:ВСПЫХНУТЬ{}, // под потолком вспыхнула яркая лампа (ВСПЫХНУТЬ)
rus_verbs:СМОТРЕТЬ{}, // просто смотрите под другим углом (СМОТРЕТЬ ПОД)
rus_verbs:ДУТЬ{}, // теперь под деревьями дул ветерок (ДУТЬ)
rus_verbs:СКРЫТЬСЯ{}, // оно быстро скрылось под водой (СКРЫТЬСЯ ПОД)
rus_verbs:ЩЕЛКНУТЬ{}, // далеко под ними щелкнул выстрел (ЩЕЛКНУТЬ)
rus_verbs:ТРЕЩАТЬ{}, // осколки стекла трещали под ногами (ТРЕЩАТЬ)
rus_verbs:РАСПОЛАГАТЬСЯ{}, // под ними располагались разноцветные скамьи (РАСПОЛАГАТЬСЯ)
rus_verbs:ВЫСТУПИТЬ{}, // под ногтями выступили капельки крови (ВЫСТУПИТЬ)
rus_verbs:НАСТУПИТЬ{}, // под куполом базы наступила тишина (НАСТУПИТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // повозка остановилась под самым окном (ОСТАНОВИТЬСЯ)
rus_verbs:РАСТАЯТЬ{}, // магазин растаял под ночным дождем (РАСТАЯТЬ)
rus_verbs:ДВИГАТЬСЯ{}, // под водой двигалось нечто огромное (ДВИГАТЬСЯ)
rus_verbs:БЫТЬ{}, // под снегом могут быть трещины (БЫТЬ)
rus_verbs:ЗИЯТЬ{}, // под ней зияла ужасная рана (ЗИЯТЬ)
rus_verbs:ЗАЗВОНИТЬ{}, // под рукой водителя зазвонил телефон (ЗАЗВОНИТЬ)
rus_verbs:ПОКАЗАТЬСЯ{}, // внезапно под ними показалась вода (ПОКАЗАТЬСЯ)
rus_verbs:ЗАМЕРЕТЬ{}, // эхо замерло под высоким потолком (ЗАМЕРЕТЬ)
rus_verbs:ПОЙТИ{}, // затем под кораблем пошла пустыня (ПОЙТИ)
rus_verbs:ДЕЙСТВОВАТЬ{}, // боги всегда действуют под маской (ДЕЙСТВОВАТЬ)
rus_verbs:БЛЕСТЕТЬ{}, // мокрый мех блестел под луной (БЛЕСТЕТЬ)
rus_verbs:ЛЕТЕТЬ{}, // под ним летела серая земля (ЛЕТЕТЬ)
rus_verbs:СОГНУТЬСЯ{}, // содрогнулся под ногами каменный пол (СОГНУТЬСЯ)
rus_verbs:КИВНУТЬ{}, // четвертый слегка кивнул под капюшоном (КИВНУТЬ)
rus_verbs:УМЕРЕТЬ{}, // колдун умер под грудой каменных глыб (УМЕРЕТЬ)
rus_verbs:ОКАЗЫВАТЬСЯ{}, // внезапно под ногами оказывается знакомая тропинка (ОКАЗЫВАТЬСЯ)
rus_verbs:ИСЧЕЗАТЬ{}, // серая лента дороги исчезала под воротами (ИСЧЕЗАТЬ)
rus_verbs:СВЕРКНУТЬ{}, // голубые глаза сверкнули под густыми бровями (СВЕРКНУТЬ)
rus_verbs:СИЯТЬ{}, // под ним сияла белая пелена облаков (СИЯТЬ)
rus_verbs:ПРОНЕСТИСЬ{}, // тихий смех пронесся под куполом зала (ПРОНЕСТИСЬ)
rus_verbs:СКОЛЬЗИТЬ{}, // обломки судна медленно скользили под ними (СКОЛЬЗИТЬ)
rus_verbs:ВЗДУТЬСЯ{}, // под серой кожей вздулись шары мускулов (ВЗДУТЬСЯ)
rus_verbs:ПРОЙТИ{}, // обломок отлично пройдет под колесами слева (ПРОЙТИ)
rus_verbs:РАЗВЕВАТЬСЯ{}, // светлые волосы развевались под дыханием ветра (РАЗВЕВАТЬСЯ)
rus_verbs:СВЕРКАТЬ{}, // глаза огнем сверкали под темными бровями (СВЕРКАТЬ)
rus_verbs:КАЗАТЬСЯ{}, // деревянный док казался очень твердым под моими ногами (КАЗАТЬСЯ)
rus_verbs:ПОСТАВИТЬ{}, // четвертый маг торопливо поставил под зеркалом широкую чашу (ПОСТАВИТЬ)
rus_verbs:ОСТАВАТЬСЯ{}, // запасы остаются под давлением (ОСТАВАТЬСЯ ПОД)
rus_verbs:ПЕТЬ{}, // просто мы под землей любим петь. (ПЕТЬ ПОД)
rus_verbs:ПОЯВИТЬСЯ{}, // под их крыльями внезапно появился дым. (ПОЯВИТЬСЯ ПОД)
rus_verbs:ОКАЗАТЬСЯ{}, // мы снова оказались под солнцем. (ОКАЗАТЬСЯ ПОД)
rus_verbs:ПОДХОДИТЬ{}, // мы подходили под другим углом? (ПОДХОДИТЬ ПОД)
rus_verbs:СКРЫВАТЬСЯ{}, // кто под ней скрывается? (СКРЫВАТЬСЯ ПОД)
rus_verbs:ХЛЮПАТЬ{}, // под ногами Аллы хлюпала грязь (ХЛЮПАТЬ ПОД)
rus_verbs:ШАГАТЬ{}, // их отряд весело шагал под дождем этой музыки. (ШАГАТЬ ПОД)
rus_verbs:ТЕЧЬ{}, // под ее поверхностью медленно текла ярость. (ТЕЧЬ ПОД твор)
rus_verbs:ОЧУТИТЬСЯ{}, // мы очутились под стенами замка. (ОЧУТИТЬСЯ ПОД)
rus_verbs:ПОБЛЕСКИВАТЬ{}, // их латы поблескивали под солнцем. (ПОБЛЕСКИВАТЬ ПОД)
rus_verbs:ДРАТЬСЯ{}, // под столами дрались за кости псы. (ДРАТЬСЯ ПОД)
rus_verbs:КАЧНУТЬСЯ{}, // палуба качнулась у нас под ногами. (КАЧНУЛАСЬ ПОД)
rus_verbs:ПРИСЕСТЬ{}, // конь даже присел под тяжелым телом. (ПРИСЕСТЬ ПОД)
rus_verbs:ЖИТЬ{}, // они живут под землей. (ЖИТЬ ПОД)
rus_verbs:ОБНАРУЖИТЬ{}, // вы можете обнаружить ее под водой? (ОБНАРУЖИТЬ ПОД)
rus_verbs:ПЛЫТЬ{}, // Орёл плывёт под облаками. (ПЛЫТЬ ПОД)
rus_verbs:ИСЧЕЗНУТЬ{}, // потом они исчезли под водой. (ИСЧЕЗНУТЬ ПОД)
rus_verbs:держать{}, // оружие все держали под рукой. (держать ПОД)
rus_verbs:ВСТРЕТИТЬСЯ{}, // они встретились под водой. (ВСТРЕТИТЬСЯ ПОД)
rus_verbs:уснуть{}, // Миша уснет под одеялом
rus_verbs:пошевелиться{}, // пошевелиться под одеялом
rus_verbs:задохнуться{}, // задохнуться под слоем снега
rus_verbs:потечь{}, // потечь под избыточным давлением
rus_verbs:уцелеть{}, // уцелеть под завалами
rus_verbs:мерцать{}, // мерцать под лучами софитов
rus_verbs:поискать{}, // поискать под кроватью
rus_verbs:гудеть{}, // гудеть под нагрузкой
rus_verbs:посидеть{}, // посидеть под навесом
rus_verbs:укрыться{}, // укрыться под навесом
rus_verbs:утихнуть{}, // утихнуть под одеялом
rus_verbs:заскрипеть{}, // заскрипеть под тяжестью
rus_verbs:шелохнуться{}, // шелохнуться под одеялом
инфинитив:срезать{ вид:несоверш }, глагол:срезать{ вид:несоверш }, // срезать под корень
деепричастие:срезав{}, прилагательное:срезающий{ вид:несоверш },
инфинитив:срезать{ вид:соверш }, глагол:срезать{ вид:соверш },
деепричастие:срезая{}, прилагательное:срезавший{ вид:соверш },
rus_verbs:пониматься{}, // пониматься под успехом
rus_verbs:подразумеваться{}, // подразумеваться под правильным решением
rus_verbs:промокнуть{}, // промокнуть под проливным дождем
rus_verbs:засосать{}, // засосать под ложечкой
rus_verbs:подписаться{}, // подписаться под воззванием
rus_verbs:укрываться{}, // укрываться под навесом
rus_verbs:запыхтеть{}, // запыхтеть под одеялом
rus_verbs:мокнуть{}, // мокнуть под лождем
rus_verbs:сгибаться{}, // сгибаться под тяжестью снега
rus_verbs:намокнуть{}, // намокнуть под дождем
rus_verbs:подписываться{}, // подписываться под обращением
rus_verbs:тарахтеть{}, // тарахтеть под окнами
инфинитив:находиться{вид:несоверш}, глагол:находиться{вид:несоверш}, // Она уже несколько лет находится под наблюдением врача.
деепричастие:находясь{}, прилагательное:находившийся{вид:несоверш}, прилагательное:находящийся{},
rus_verbs:лежать{}, // лежать под капельницей
rus_verbs:вымокать{}, // вымокать под дождём
rus_verbs:вымокнуть{}, // вымокнуть под дождём
rus_verbs:проворчать{}, // проворчать под нос
rus_verbs:хмыкнуть{}, // хмыкнуть под нос
rus_verbs:отыскать{}, // отыскать под кроватью
rus_verbs:дрогнуть{}, // дрогнуть под ударами
rus_verbs:проявляться{}, // проявляться под нагрузкой
rus_verbs:сдержать{}, // сдержать под контролем
rus_verbs:ложиться{}, // ложиться под клиента
rus_verbs:таять{}, // таять под весенним солнцем
rus_verbs:покатиться{}, // покатиться под откос
rus_verbs:лечь{}, // он лег под навесом
rus_verbs:идти{}, // идти под дождем
прилагательное:известный{}, // Он известен под этим именем.
rus_verbs:стоять{}, // Ящик стоит под столом.
rus_verbs:отступить{}, // Враг отступил под ударами наших войск.
rus_verbs:царапаться{}, // Мышь царапается под полом.
rus_verbs:спать{}, // заяц спокойно спал у себя под кустом
rus_verbs:загорать{}, // мы загораем под солнцем
ГЛ_ИНФ(мыть), // мыть руки под струёй воды
ГЛ_ИНФ(закопать),
ГЛ_ИНФ(спрятать),
ГЛ_ИНФ(прятать),
ГЛ_ИНФ(перепрятать)
}
fact гл_предл
{
if context { Гл_ПОД_твор предлог:под{} *:*{ падеж:твор } }
then return true
}
// для глаголов вне списка - запрещаем.
fact гл_предл
{
if context { * предлог:под{} *:*{ падеж:твор } }
then return false,-10
}
fact гл_предл
{
if context { * предлог:под{} *:*{} }
then return false,-11
}
#endregion Предлог_ПОД
*/
#region Предлог_ОБ
// -------------- ПРЕДЛОГ 'ОБ' -----------------------
wordentry_set Гл_ОБ_предл=
{
rus_verbs:СВИДЕТЕЛЬСТВОВАТЬ{}, // Об их присутствии свидетельствовало лишь тусклое пурпурное пятно, проступавшее на камне. (СВИДЕТЕЛЬСТВОВАТЬ)
rus_verbs:ЗАДУМАТЬСЯ{}, // Промышленные гиганты задумались об экологии (ЗАДУМАТЬСЯ)
rus_verbs:СПРОСИТЬ{}, // Он спросил нескольких из пляжников об их кажущейся всеобщей юности. (СПРОСИТЬ)
rus_verbs:спрашивать{}, // как ты можешь еще спрашивать у меня об этом?
rus_verbs:забывать{}, // Мы не можем забывать об их участи.
rus_verbs:ГАДАТЬ{}, // теперь об этом можно лишь гадать (ГАДАТЬ)
rus_verbs:ПОВЕДАТЬ{}, // Градоначальник , выступая с обзором основных городских событий , поведал об этом депутатам (ПОВЕДАТЬ ОБ)
rus_verbs:СООБЩИТЬ{}, // Иран сообщил МАГАТЭ об ускорении обогащения урана (СООБЩИТЬ)
rus_verbs:ЗАЯВИТЬ{}, // Об их успешном окончании заявил генеральный директор (ЗАЯВИТЬ ОБ)
rus_verbs:слышать{}, // даже они слышали об этом человеке. (СЛЫШАТЬ ОБ)
rus_verbs:ДОЛОЖИТЬ{}, // вернувшиеся разведчики доложили об увиденном (ДОЛОЖИТЬ ОБ)
rus_verbs:ПОГОВОРИТЬ{}, // давай поговорим об этом. (ПОГОВОРИТЬ ОБ)
rus_verbs:ДОГАДАТЬСЯ{}, // об остальном нетрудно догадаться. (ДОГАДАТЬСЯ ОБ)
rus_verbs:ПОЗАБОТИТЬСЯ{}, // обещал обо всем позаботиться. (ПОЗАБОТИТЬСЯ ОБ)
rus_verbs:ПОЗАБЫТЬ{}, // Шура позабыл обо всем. (ПОЗАБЫТЬ ОБ)
rus_verbs:вспоминать{}, // Впоследствии он не раз вспоминал об этом приключении. (вспоминать об)
rus_verbs:сообщать{}, // Газета сообщает об открытии сессии парламента. (сообщать об)
rus_verbs:просить{}, // мы просили об отсрочке платежей (просить ОБ)
rus_verbs:ПЕТЬ{}, // эта же девушка пела обо всем совершенно открыто. (ПЕТЬ ОБ)
rus_verbs:сказать{}, // ты скажешь об этом капитану? (сказать ОБ)
rus_verbs:знать{}, // бы хотелось знать как можно больше об этом районе.
rus_verbs:кричать{}, // Все газеты кричат об этом событии.
rus_verbs:советоваться{}, // Она обо всём советуется с матерью.
rus_verbs:говориться{}, // об остальном говорилось легко.
rus_verbs:подумать{}, // нужно крепко обо всем подумать.
rus_verbs:напомнить{}, // черный дым напомнил об опасности.
rus_verbs:забыть{}, // забудь об этой роскоши.
rus_verbs:думать{}, // приходится обо всем думать самой.
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:информировать{}, // информировать об изменениях
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:заговорить{}, // заговорить об оплате
rus_verbs:отозваться{}, // Он отозвался об этой книге с большой похвалой.
rus_verbs:попросить{}, // попросить об услуге
rus_verbs:объявить{}, // объявить об отставке
rus_verbs:предупредить{}, // предупредить об аварии
rus_verbs:предупреждать{}, // предупреждать об опасности
rus_verbs:твердить{}, // твердить об обязанностях
rus_verbs:заявлять{}, // заявлять об экспериментальном подтверждении
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
rus_verbs:говорить{}, // Не говорите об этом в присутствии третьих лиц.
rus_verbs:читать{}, // он читал об этом в журнале
rus_verbs:прочитать{}, // он читал об этом в учебнике
rus_verbs:узнать{}, // он узнал об этом из фильмов
rus_verbs:рассказать{}, // рассказать об экзаменах
rus_verbs:рассказывать{},
rus_verbs:договориться{}, // договориться об оплате
rus_verbs:договариваться{}, // договариваться об обмене
rus_verbs:болтать{}, // Не болтай об этом!
rus_verbs:проболтаться{}, // Не проболтайся об этом!
rus_verbs:заботиться{}, // кто заботится об урегулировании
rus_verbs:беспокоиться{}, // вы беспокоитесь об обороне
rus_verbs:помнить{}, // всем советую об этом помнить
rus_verbs:мечтать{} // Мечтать об успехе
}
fact гл_предл
{
if context { Гл_ОБ_предл предлог:об{} *:*{ падеж:предл } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} @regex("[a-z]+[0-9]*") }
then return true
}
fact гл_предл
{
if context { * предлог:об{} @regex("[a-z]+[0-9]*") }
then return true
}
// остальные глаголы не могут связываться
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:предл } }
then return false, -4
}
wordentry_set Гл_ОБ_вин=
{
rus_verbs:СЛОМАТЬ{}, // потом об колено сломал (СЛОМАТЬ)
rus_verbs:разбить{}, // ты разбил щеку об угол ящика. (РАЗБИТЬ ОБ)
rus_verbs:опереться{}, // Он опёрся об стену.
rus_verbs:опираться{},
rus_verbs:постучать{}, // постучал лбом об пол.
rus_verbs:удариться{}, // бутылка глухо ударилась об землю.
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:царапаться{} // Днище лодки царапалось обо что-то.
}
fact гл_предл
{
if context { Гл_ОБ_вин предлог:об{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:об{} *:*{ падеж:вин } }
then return false,-4
}
fact гл_предл
{
if context { * предлог:об{} *:*{} }
then return false,-5
}
#endregion Предлог_ОБ
#region Предлог_О
// ------------------- С ПРЕДЛОГОМ 'О' ----------------------
wordentry_set Гл_О_Вин={
rus_verbs:шмякнуть{}, // Ей хотелось шмякнуть ими о стену.
rus_verbs:болтать{}, // Болтали чаще всего о пустяках.
rus_verbs:шваркнуть{}, // Она шваркнула трубкой о рычаг.
rus_verbs:опираться{}, // Мать приподнялась, с трудом опираясь о стол.
rus_verbs:бахнуться{}, // Бахнуться головой о стол.
rus_verbs:ВЫТЕРЕТЬ{}, // Вытащи нож и вытри его о траву. (ВЫТЕРЕТЬ/ВЫТИРАТЬ)
rus_verbs:ВЫТИРАТЬ{}, //
rus_verbs:РАЗБИТЬСЯ{}, // Прибой накатился и с шумом разбился о белый песок. (РАЗБИТЬСЯ)
rus_verbs:СТУКНУТЬ{}, // Сердце его глухо стукнуло о грудную кость (СТУКНУТЬ)
rus_verbs:ЛЯЗГНУТЬ{}, // Он кинулся наземь, покатился, и копье лязгнуло о стену. (ЛЯЗГНУТЬ/ЛЯЗГАТЬ)
rus_verbs:ЛЯЗГАТЬ{}, //
rus_verbs:звенеть{}, // стрелы уже звенели о прутья клетки
rus_verbs:ЩЕЛКНУТЬ{}, // камень щелкнул о скалу (ЩЕЛКНУТЬ)
rus_verbs:БИТЬ{}, // волна бьет о берег (БИТЬ)
rus_verbs:ЗАЗВЕНЕТЬ{}, // зазвенели мечи о щиты (ЗАЗВЕНЕТЬ)
rus_verbs:колотиться{}, // сердце его колотилось о ребра
rus_verbs:стучать{}, // глухо стучали о щиты рукояти мечей.
rus_verbs:биться{}, // биться головой о стену? (биться о)
rus_verbs:ударить{}, // вода ударила его о стену коридора. (ударила о)
rus_verbs:разбиваться{}, // волны разбивались о скалу
rus_verbs:разбивать{}, // Разбивает голову о прутья клетки.
rus_verbs:облокотиться{}, // облокотиться о стену
rus_verbs:точить{}, // точить о точильный камень
rus_verbs:спотыкаться{}, // спотыкаться о спрятавшийся в траве пень
rus_verbs:потереться{}, // потереться о дерево
rus_verbs:ушибиться{}, // ушибиться о дерево
rus_verbs:тереться{}, // тереться о ствол
rus_verbs:шмякнуться{}, // шмякнуться о землю
rus_verbs:убиваться{}, // убиваться об стену
rus_verbs:расшибить{}, // расшибить об стену
rus_verbs:тереть{}, // тереть о камень
rus_verbs:потереть{}, // потереть о колено
rus_verbs:удариться{}, // удариться о край
rus_verbs:споткнуться{}, // споткнуться о камень
rus_verbs:запнуться{}, // запнуться о камень
rus_verbs:запинаться{}, // запинаться о камни
rus_verbs:ударяться{}, // ударяться о бортик
rus_verbs:стукнуться{}, // стукнуться о бортик
rus_verbs:стукаться{}, // стукаться о бортик
rus_verbs:опереться{}, // Он опёрся локтями о стол.
rus_verbs:плескаться{} // Вода плещется о берег.
}
fact гл_предл
{
if context { Гл_О_Вин предлог:о{} *:*{ падеж:вин } }
then return true
}
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:вин } }
then return false,-5
}
wordentry_set Гл_О_предл={
rus_verbs:КРИЧАТЬ{}, // она кричала о смерти! (КРИЧАТЬ)
rus_verbs:РАССПРОСИТЬ{}, // Я расспросил о нем нескольких горожан. (РАССПРОСИТЬ/РАССПРАШИВАТЬ)
rus_verbs:РАССПРАШИВАТЬ{}, //
rus_verbs:слушать{}, // ты будешь слушать о них?
rus_verbs:вспоминать{}, // вспоминать о том разговоре ему было неприятно
rus_verbs:МОЛЧАТЬ{}, // О чём молчат девушки (МОЛЧАТЬ)
rus_verbs:ПЛАКАТЬ{}, // она плакала о себе (ПЛАКАТЬ)
rus_verbs:сложить{}, // о вас сложены легенды
rus_verbs:ВОЛНОВАТЬСЯ{}, // Я волнуюсь о том, что что-то серьёзно пошло не так (ВОЛНОВАТЬСЯ О)
rus_verbs:УПОМЯНУТЬ{}, // упомянул о намерении команды приобрести несколько новых футболистов (УПОМЯНУТЬ О)
rus_verbs:ОТЧИТЫВАТЬСЯ{}, // Судебные приставы продолжают отчитываться о борьбе с неплательщиками (ОТЧИТЫВАТЬСЯ О)
rus_verbs:ДОЛОЖИТЬ{}, // провести тщательное расследование взрыва в маршрутном такси во Владикавказе и доложить о результатах (ДОЛОЖИТЬ О)
rus_verbs:ПРОБОЛТАТЬ{}, // правительство страны больше проболтало о военной реформе (ПРОБОЛТАТЬ О)
rus_verbs:ЗАБОТИТЬСЯ{}, // Четверть россиян заботятся о здоровье путем просмотра телевизора (ЗАБОТИТЬСЯ О)
rus_verbs:ИРОНИЗИРОВАТЬ{}, // Вы иронизируете о ностальгии по тем временем (ИРОНИЗИРОВАТЬ О)
rus_verbs:СИГНАЛИЗИРОВАТЬ{}, // Кризис цен на продукты питания сигнализирует о неминуемой гиперинфляции (СИГНАЛИЗИРОВАТЬ О)
rus_verbs:СПРОСИТЬ{}, // Он спросил о моём здоровье. (СПРОСИТЬ О)
rus_verbs:НАПОМНИТЬ{}, // больной зуб опять напомнил о себе. (НАПОМНИТЬ О)
rus_verbs:осведомиться{}, // офицер осведомился о цели визита
rus_verbs:объявить{}, // В газете объявили о конкурсе. (объявить о)
rus_verbs:ПРЕДСТОЯТЬ{}, // о чем предстоит разговор? (ПРЕДСТОЯТЬ О)
rus_verbs:объявлять{}, // объявлять о всеобщей забастовке (объявлять о)
rus_verbs:зайти{}, // Разговор зашёл о политике.
rus_verbs:порассказать{}, // порассказать о своих путешествиях
инфинитив:спеть{ вид:соверш }, глагол:спеть{ вид:соверш }, // спеть о неразделенной любви
деепричастие:спев{}, прилагательное:спевший{ вид:соверш },
прилагательное:спетый{},
rus_verbs:напеть{},
rus_verbs:разговаривать{}, // разговаривать с другом о жизни
rus_verbs:рассуждать{}, // рассуждать об абстрактных идеях
//rus_verbs:заботиться{}, // заботиться о престарелых родителях
rus_verbs:раздумывать{}, // раздумывать о новой работе
rus_verbs:договариваться{}, // договариваться о сумме компенсации
rus_verbs:молить{}, // молить о пощаде
rus_verbs:отзываться{}, // отзываться о книге
rus_verbs:подумывать{}, // подумывать о новом подходе
rus_verbs:поговаривать{}, // поговаривать о загадочном звере
rus_verbs:обмолвиться{}, // обмолвиться о проклятии
rus_verbs:условиться{}, // условиться о поддержке
rus_verbs:призадуматься{}, // призадуматься о последствиях
rus_verbs:известить{}, // известить о поступлении
rus_verbs:отрапортовать{}, // отрапортовать об успехах
rus_verbs:напевать{}, // напевать о любви
rus_verbs:помышлять{}, // помышлять о новом деле
rus_verbs:переговорить{}, // переговорить о правилах
rus_verbs:повествовать{}, // повествовать о событиях
rus_verbs:слыхивать{}, // слыхивать о чудище
rus_verbs:потолковать{}, // потолковать о планах
rus_verbs:проговориться{}, // проговориться о планах
rus_verbs:умолчать{}, // умолчать о штрафах
rus_verbs:хлопотать{}, // хлопотать о премии
rus_verbs:уведомить{}, // уведомить о поступлении
rus_verbs:горевать{}, // горевать о потере
rus_verbs:запамятовать{}, // запамятовать о важном мероприятии
rus_verbs:заикнуться{}, // заикнуться о прибавке
rus_verbs:информировать{}, // информировать о событиях
rus_verbs:проболтаться{}, // проболтаться о кладе
rus_verbs:поразмыслить{}, // поразмыслить о судьбе
rus_verbs:заикаться{}, // заикаться о деньгах
rus_verbs:оповестить{}, // оповестить об отказе
rus_verbs:печься{}, // печься о всеобщем благе
rus_verbs:разглагольствовать{}, // разглагольствовать о правах
rus_verbs:размечтаться{}, // размечтаться о будущем
rus_verbs:лепетать{}, // лепетать о невиновности
rus_verbs:грезить{}, // грезить о большой и чистой любви
rus_verbs:залепетать{}, // залепетать о сокровищах
rus_verbs:пронюхать{}, // пронюхать о бесплатной одежде
rus_verbs:протрубить{}, // протрубить о победе
rus_verbs:извещать{}, // извещать о поступлении
rus_verbs:трубить{}, // трубить о поимке разбойников
rus_verbs:осведомляться{}, // осведомляться о судьбе
rus_verbs:поразмышлять{}, // поразмышлять о неизбежном
rus_verbs:слагать{}, // слагать о подвигах викингов
rus_verbs:ходатайствовать{}, // ходатайствовать о выделении материальной помощи
rus_verbs:побеспокоиться{}, // побеспокоиться о правильном стимулировании
rus_verbs:закидывать{}, // закидывать сообщениями об ошибках
rus_verbs:базарить{}, // пацаны базарили о телках
rus_verbs:балагурить{}, // мужики балагурили о новом председателе
rus_verbs:балакать{}, // мужики балакали о новом председателе
rus_verbs:беспокоиться{}, // Она беспокоится о детях
rus_verbs:рассказать{}, // Кумир рассказал о криминале в Москве
rus_verbs:возмечтать{}, // возмечтать о счастливом мире
rus_verbs:вопить{}, // Кто-то вопил о несправедливости
rus_verbs:сказать{}, // сказать что-то новое о ком-то
rus_verbs:знать{}, // знать о ком-то что-то пикантное
rus_verbs:подумать{}, // подумать о чём-то
rus_verbs:думать{}, // думать о чём-то
rus_verbs:узнать{}, // узнать о происшествии
rus_verbs:помнить{}, // помнить о задании
rus_verbs:просить{}, // просить о коде доступа
rus_verbs:забыть{}, // забыть о своих обязанностях
rus_verbs:сообщить{}, // сообщить о заложенной мине
rus_verbs:заявить{}, // заявить о пропаже
rus_verbs:задуматься{}, // задуматься о смерти
rus_verbs:спрашивать{}, // спрашивать о поступлении товара
rus_verbs:догадаться{}, // догадаться о причинах
rus_verbs:договориться{}, // договориться о собеседовании
rus_verbs:мечтать{}, // мечтать о сцене
rus_verbs:поговорить{}, // поговорить о наболевшем
rus_verbs:размышлять{}, // размышлять о насущном
rus_verbs:напоминать{}, // напоминать о себе
rus_verbs:пожалеть{}, // пожалеть о содеянном
rus_verbs:ныть{}, // ныть о прибавке
rus_verbs:сообщать{}, // сообщать о победе
rus_verbs:догадываться{}, // догадываться о первопричине
rus_verbs:поведать{}, // поведать о тайнах
rus_verbs:умолять{}, // умолять о пощаде
rus_verbs:сожалеть{}, // сожалеть о случившемся
rus_verbs:жалеть{}, // жалеть о случившемся
rus_verbs:забывать{}, // забывать о случившемся
rus_verbs:упоминать{}, // упоминать о предках
rus_verbs:позабыть{}, // позабыть о своем обещании
rus_verbs:запеть{}, // запеть о любви
rus_verbs:скорбеть{}, // скорбеть о усопшем
rus_verbs:задумываться{}, // задумываться о смене работы
rus_verbs:позаботиться{}, // позаботиться о престарелых родителях
rus_verbs:докладывать{}, // докладывать о планах строительства целлюлозно-бумажного комбината
rus_verbs:попросить{}, // попросить о замене
rus_verbs:предупредить{}, // предупредить о замене
rus_verbs:предупреждать{}, // предупреждать о замене
rus_verbs:твердить{}, // твердить о замене
rus_verbs:заявлять{}, // заявлять о подлоге
rus_verbs:петь{}, // певица, поющая о лете
rus_verbs:проинформировать{}, // проинформировать о переговорах
rus_verbs:порассказывать{}, // порассказывать о событиях
rus_verbs:послушать{}, // послушать о новинках
rus_verbs:заговорить{}, // заговорить о плате
rus_verbs:отозваться{}, // Он отозвался о книге с большой похвалой.
rus_verbs:оставить{}, // Он оставил о себе печальную память.
rus_verbs:свидетельствовать{}, // страшно исхудавшее тело свидетельствовало о долгих лишениях
rus_verbs:спорить{}, // они спорили о законе
глагол:написать{ aux stress="напис^ать" }, инфинитив:написать{ aux stress="напис^ать" }, // Он написал о том, что видел во время путешествия.
глагол:писать{ aux stress="пис^ать" }, инфинитив:писать{ aux stress="пис^ать" }, // Он писал о том, что видел во время путешествия.
rus_verbs:прочитать{}, // Я прочитал о тебе
rus_verbs:услышать{}, // Я услышал о нем
rus_verbs:помечтать{}, // Девочки помечтали о принце
rus_verbs:слышать{}, // Мальчик слышал о приведениях
rus_verbs:вспомнить{}, // Девочки вспомнили о завтраке
rus_verbs:грустить{}, // Я грущу о тебе
rus_verbs:осведомить{}, // о последних достижениях науки
rus_verbs:рассказывать{}, // Антонио рассказывает о работе
rus_verbs:говорить{}, // говорим о трех больших псах
rus_verbs:идти{} // Вопрос идёт о войне.
}
fact гл_предл
{
if context { Гл_О_предл предлог:о{} *:*{ падеж:предл } }
then return true
}
// Мы поделились впечатлениями о выставке.
// ^^^^^^^^^^ ^^^^^^^^^^
fact гл_предл
{
if context { * предлог:о{} *:*{ падеж:предл } }
then return false,-3
}
fact гл_предл
{
if context { * предлог:о{} *:*{} }
then return false,-5
}
#endregion Предлог_О
#region Предлог_ПО
// ------------------- С ПРЕДЛОГОМ 'ПО' ----------------------
// для этих глаголов - запрещаем связывание с ПО+дат.п.
wordentry_set Глаг_ПО_Дат_Запр=
{
rus_verbs:предпринять{}, // предпринять шаги по стимулированию продаж
rus_verbs:увлечь{}, // увлечь в прогулку по парку
rus_verbs:закончить{},
rus_verbs:мочь{},
rus_verbs:хотеть{}
}
fact гл_предл
{
if context { Глаг_ПО_Дат_Запр предлог:по{} *:*{ падеж:дат } }
then return false,-10
}
// По умолчанию разрешаем связывание в паттернах типа
// Я иду по шоссе
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:дат } }
then return true
}
wordentry_set Глаг_ПО_Вин=
{
rus_verbs:ВОЙТИ{}, // лезвие вошло по рукоять (ВОЙТИ)
rus_verbs:иметь{}, // все месяцы имели по тридцать дней. (ИМЕТЬ ПО)
rus_verbs:материализоваться{}, // материализоваться по другую сторону барьера
rus_verbs:засадить{}, // засадить по рукоятку
rus_verbs:увязнуть{} // увязнуть по колено
}
fact гл_предл
{
if context { Глаг_ПО_Вин предлог:по{} *:*{ падеж:вин } }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:по{} *:*{ падеж:вин } }
then return false,-5
}
#endregion Предлог_ПО
#region Предлог_К
// ------------------- С ПРЕДЛОГОМ 'К' ----------------------
wordentry_set Гл_К_Дат={
rus_verbs:заявиться{}, // Сразу же после обеда к нам заявилась Юлия Михайловна.
rus_verbs:приставлять{} , // Приставляет дуло пистолета к виску.
прилагательное:НЕПРИГОДНЫЙ{}, // большинство компьютеров из этой партии оказались непригодными к эксплуатации (НЕПРИГОДНЫЙ)
rus_verbs:СБЕГАТЬСЯ{}, // Они чуяли воду и сбегались к ней отовсюду. (СБЕГАТЬСЯ)
rus_verbs:СБЕЖАТЬСЯ{}, // К бетонной скамье начали сбегаться люди. (СБЕГАТЬСЯ/СБЕЖАТЬСЯ)
rus_verbs:ПРИТИРАТЬСЯ{}, // Менее стойких водителей буквально сметало на другую полосу, и они впритык притирались к другим машинам. (ПРИТИРАТЬСЯ)
rus_verbs:РУХНУТЬ{}, // а потом ты без чувств рухнул к моим ногам (РУХНУТЬ)
rus_verbs:ПЕРЕНЕСТИ{}, // Они перенесли мясо к ручью и поджарили его на костре. (ПЕРЕНЕСТИ)
rus_verbs:ЗАВЕСТИ{}, // как путь мой завел меня к нему? (ЗАВЕСТИ)
rus_verbs:НАГРЯНУТЬ{}, // ФБР нагрянуло с обыском к сестре бостонских террористов (НАГРЯНУТЬ)
rus_verbs:ПРИСЛОНЯТЬСЯ{}, // Рабы ложились на пол, прислонялись к стене и спали. (ПРИСЛОНЯТЬСЯ,ПРИНОРАВЛИВАТЬСЯ,ПРИНОРОВИТЬСЯ)
rus_verbs:ПРИНОРАВЛИВАТЬСЯ{}, //
rus_verbs:ПРИНОРОВИТЬСЯ{}, //
rus_verbs:СПЛАНИРОВАТЬ{}, // Вскоре она остановила свое падение и спланировала к ним. (СПЛАНИРОВАТЬ,СПИКИРОВАТЬ,РУХНУТЬ)
rus_verbs:СПИКИРОВАТЬ{}, //
rus_verbs:ЗАБРАТЬСЯ{}, // Поэтому он забрался ко мне в квартиру с имевшимся у него полумесяцем. (ЗАБРАТЬСЯ К, В, С)
rus_verbs:ПРОТЯГИВАТЬ{}, // Оно протягивало свои длинные руки к молодому человеку, стоявшему на плоской вершине валуна. (ПРОТЯГИВАТЬ/ПРОТЯНУТЬ/ТЯНУТЬ)
rus_verbs:ПРОТЯНУТЬ{}, //
rus_verbs:ТЯНУТЬ{}, //
rus_verbs:ПЕРЕБИРАТЬСЯ{}, // Ее губы медленно перебирались к его уху. (ПЕРЕБИРАТЬСЯ,ПЕРЕБРАТЬСЯ,ПЕРЕБАЗИРОВАТЬСЯ,ПЕРЕМЕСТИТЬСЯ,ПЕРЕМЕЩАТЬСЯ)
rus_verbs:ПЕРЕБРАТЬСЯ{}, // ,,,
rus_verbs:ПЕРЕБАЗИРОВАТЬСЯ{}, //
rus_verbs:ПЕРЕМЕСТИТЬСЯ{}, //
rus_verbs:ПЕРЕМЕЩАТЬСЯ{}, //
rus_verbs:ТРОНУТЬСЯ{}, // Он отвернулся от нее и тронулся к пляжу. (ТРОНУТЬСЯ)
rus_verbs:ПРИСТАВИТЬ{}, // Он поднял одну из них и приставил верхний конец к краю шахты в потолке.
rus_verbs:ПРОБИТЬСЯ{}, // Отряд с невероятными приключениями, пытается пробиться к своему полку, попадает в плен и другие передряги (ПРОБИТЬСЯ)
rus_verbs:хотеть{},
rus_verbs:СДЕЛАТЬ{}, // Сделайте всё к понедельнику (СДЕЛАТЬ)
rus_verbs:ИСПЫТЫВАТЬ{}, // она испытывает ко мне только отвращение (ИСПЫТЫВАТЬ)
rus_verbs:ОБЯЗЫВАТЬ{}, // Это меня ни к чему не обязывает (ОБЯЗЫВАТЬ)
rus_verbs:КАРАБКАТЬСЯ{}, // карабкаться по горе от подножия к вершине (КАРАБКАТЬСЯ)
rus_verbs:СТОЯТЬ{}, // мужчина стоял ко мне спиной (СТОЯТЬ)
rus_verbs:ПОДАТЬСЯ{}, // наконец люк подался ко мне (ПОДАТЬСЯ)
rus_verbs:ПРИРАВНЯТЬ{}, // Усилия нельзя приравнять к результату (ПРИРАВНЯТЬ)
rus_verbs:ПРИРАВНИВАТЬ{}, // Усилия нельзя приравнивать к результату (ПРИРАВНИВАТЬ)
rus_verbs:ВОЗЛОЖИТЬ{}, // Путин в Пскове возложил цветы к памятнику воинам-десантникам, погибшим в Чечне (ВОЗЛОЖИТЬ)
rus_verbs:запустить{}, // Индия запустит к Марсу свой космический аппарат в 2013 г
rus_verbs:ПРИСТЫКОВАТЬСЯ{}, // Роботизированный российский грузовой космический корабль пристыковался к МКС (ПРИСТЫКОВАТЬСЯ)
rus_verbs:ПРИМАЗАТЬСЯ{}, // К челябинскому метеориту примазалась таинственная слизь (ПРИМАЗАТЬСЯ)
rus_verbs:ПОПРОСИТЬ{}, // Попросите Лизу к телефону (ПОПРОСИТЬ К)
rus_verbs:ПРОЕХАТЬ{}, // Порой школьные автобусы просто не имеют возможности проехать к некоторым населенным пунктам из-за бездорожья (ПРОЕХАТЬ К)
rus_verbs:ПОДЦЕПЛЯТЬСЯ{}, // Вагоны с пассажирами подцепляются к составу (ПОДЦЕПЛЯТЬСЯ К)
rus_verbs:ПРИЗВАТЬ{}, // Президент Афганистана призвал талибов к прямому диалогу (ПРИЗВАТЬ К)
rus_verbs:ПРЕОБРАЗИТЬСЯ{}, // Культовый столичный отель преобразился к юбилею (ПРЕОБРАЗИТЬСЯ К)
прилагательное:ЧУВСТВИТЕЛЬНЫЙ{}, // нейроны одного комплекса чувствительны к разным веществам (ЧУВСТВИТЕЛЬНЫЙ К)
безлич_глагол:нужно{}, // нам нужно к воротам (НУЖНО К)
rus_verbs:БРОСИТЬ{}, // огромный клюв бросил это мясо к моим ногам (БРОСИТЬ К)
rus_verbs:ЗАКОНЧИТЬ{}, // к пяти утра техники закончили (ЗАКОНЧИТЬ К)
rus_verbs:НЕСТИ{}, // к берегу нас несет! (НЕСТИ К)
rus_verbs:ПРОДВИГАТЬСЯ{}, // племена медленно продвигались к востоку (ПРОДВИГАТЬСЯ К)
rus_verbs:ОПУСКАТЬСЯ{}, // деревья опускались к самой воде (ОПУСКАТЬСЯ К)
rus_verbs:СТЕМНЕТЬ{}, // к тому времени стемнело (СТЕМНЕЛО К)
rus_verbs:ОТСКОЧИТЬ{}, // после отскочил к окну (ОТСКОЧИТЬ К)
rus_verbs:ДЕРЖАТЬСЯ{}, // к солнцу держались спинами (ДЕРЖАТЬСЯ К)
rus_verbs:КАЧНУТЬСЯ{}, // толпа качнулась к ступеням (КАЧНУТЬСЯ К)
rus_verbs:ВОЙТИ{}, // Андрей вошел к себе (ВОЙТИ К)
rus_verbs:ВЫБРАТЬСЯ{}, // мы выбрались к окну (ВЫБРАТЬСЯ К)
rus_verbs:ПРОВЕСТИ{}, // провел к стене спальни (ПРОВЕСТИ К)
rus_verbs:ВЕРНУТЬСЯ{}, // давай вернемся к делу (ВЕРНУТЬСЯ К)
rus_verbs:ВОЗВРАТИТЬСЯ{}, // Среди евреев, живших в диаспоре, всегда было распространено сильное стремление возвратиться к Сиону (ВОЗВРАТИТЬСЯ К)
rus_verbs:ПРИЛЕГАТЬ{}, // Задняя поверхность хрусталика прилегает к стекловидному телу (ПРИЛЕГАТЬ К)
rus_verbs:ПЕРЕНЕСТИСЬ{}, // мысленно Алёна перенеслась к заливу (ПЕРЕНЕСТИСЬ К)
rus_verbs:ПРОБИВАТЬСЯ{}, // сквозь болото к берегу пробивался ручей. (ПРОБИВАТЬСЯ К)
rus_verbs:ПЕРЕВЕСТИ{}, // необходимо срочно перевести стадо к воде. (ПЕРЕВЕСТИ К)
rus_verbs:ПРИЛЕТЕТЬ{}, // зачем ты прилетел к нам? (ПРИЛЕТЕТЬ К)
rus_verbs:ДОБАВИТЬ{}, // добавить ли ее к остальным? (ДОБАВИТЬ К)
rus_verbs:ПРИГОТОВИТЬ{}, // Матвей приготовил лук к бою. (ПРИГОТОВИТЬ К)
rus_verbs:РВАНУТЬ{}, // человек рванул ее к себе. (РВАНУТЬ К)
rus_verbs:ТАЩИТЬ{}, // они тащили меня к двери. (ТАЩИТЬ К)
глагол:быть{}, // к тебе есть вопросы.
прилагательное:равнодушный{}, // Он равнодушен к музыке.
rus_verbs:ПОЖАЛОВАТЬ{}, // скандально известный певец пожаловал к нам на передачу (ПОЖАЛОВАТЬ К)
rus_verbs:ПЕРЕСЕСТЬ{}, // Ольга пересела к Антону (ПЕРЕСЕСТЬ К)
инфинитив:СБЕГАТЬ{ вид:соверш }, глагол:СБЕГАТЬ{ вид:соверш }, // сбегай к Борису (СБЕГАТЬ К)
rus_verbs:ПЕРЕХОДИТЬ{}, // право хода переходит к Адаму (ПЕРЕХОДИТЬ К)
rus_verbs:прижаться{}, // она прижалась щекой к его шее. (прижаться+к)
rus_verbs:ПОДСКОЧИТЬ{}, // солдат быстро подскочил ко мне. (ПОДСКОЧИТЬ К)
rus_verbs:ПРОБРАТЬСЯ{}, // нужно пробраться к реке. (ПРОБРАТЬСЯ К)
rus_verbs:ГОТОВИТЬ{}, // нас готовили к этому. (ГОТОВИТЬ К)
rus_verbs:ТЕЧЬ{}, // река текла к морю. (ТЕЧЬ К)
rus_verbs:ОТШАТНУТЬСЯ{}, // епископ отшатнулся к стене. (ОТШАТНУТЬСЯ К)
rus_verbs:БРАТЬ{}, // брали бы к себе. (БРАТЬ К)
rus_verbs:СКОЛЬЗНУТЬ{}, // ковер скользнул к пещере. (СКОЛЬЗНУТЬ К)
rus_verbs:присохнуть{}, // Грязь присохла к одежде. (присохнуть к)
rus_verbs:просить{}, // Директор просит вас к себе. (просить к)
rus_verbs:вызывать{}, // шеф вызывал к себе. (вызывать к)
rus_verbs:присесть{}, // старик присел к огню. (присесть к)
rus_verbs:НАКЛОНИТЬСЯ{}, // Ричард наклонился к брату. (НАКЛОНИТЬСЯ К)
rus_verbs:выбираться{}, // будем выбираться к дороге. (выбираться к)
rus_verbs:отвернуться{}, // Виктор отвернулся к стене. (отвернуться к)
rus_verbs:СТИХНУТЬ{}, // огонь стих к полудню. (СТИХНУТЬ К)
rus_verbs:УПАСТЬ{}, // нож упал к ногам. (УПАСТЬ К)
rus_verbs:СЕСТЬ{}, // молча сел к огню. (СЕСТЬ К)
rus_verbs:ХЛЫНУТЬ{}, // народ хлынул к стенам. (ХЛЫНУТЬ К)
rus_verbs:покатиться{}, // они черной волной покатились ко мне. (покатиться к)
rus_verbs:ОБРАТИТЬ{}, // она обратила к нему свое бледное лицо. (ОБРАТИТЬ К)
rus_verbs:СКЛОНИТЬ{}, // Джон слегка склонил голову к плечу. (СКЛОНИТЬ К)
rus_verbs:СВЕРНУТЬ{}, // дорожка резко свернула к южной стене. (СВЕРНУТЬ К)
rus_verbs:ЗАВЕРНУТЬ{}, // Он завернул к нам по пути к месту службы. (ЗАВЕРНУТЬ К)
rus_verbs:подходить{}, // цвет подходил ей к лицу.
rus_verbs:БРЕСТИ{}, // Ричард покорно брел к отцу. (БРЕСТИ К)
rus_verbs:ПОПАСТЬ{}, // хочешь попасть к нему? (ПОПАСТЬ К)
rus_verbs:ПОДНЯТЬ{}, // Мартин поднял ружье к плечу. (ПОДНЯТЬ К)
rus_verbs:ПОТЕРЯТЬ{}, // просто потеряла к нему интерес. (ПОТЕРЯТЬ К)
rus_verbs:РАЗВЕРНУТЬСЯ{}, // они сразу развернулись ко мне. (РАЗВЕРНУТЬСЯ К)
rus_verbs:ПОВЕРНУТЬ{}, // мальчик повернул к ним голову. (ПОВЕРНУТЬ К)
rus_verbs:вызвать{}, // или вызвать к жизни? (вызвать к)
rus_verbs:ВЫХОДИТЬ{}, // их земли выходят к морю. (ВЫХОДИТЬ К)
rus_verbs:ЕХАТЬ{}, // мы долго ехали к вам. (ЕХАТЬ К)
rus_verbs:опуститься{}, // Алиса опустилась к самому дну. (опуститься к)
rus_verbs:подняться{}, // они молча поднялись к себе. (подняться к)
rus_verbs:ДВИНУТЬСЯ{}, // толстяк тяжело двинулся к ним. (ДВИНУТЬСЯ К)
rus_verbs:ПОПЯТИТЬСЯ{}, // ведьмак осторожно попятился к лошади. (ПОПЯТИТЬСЯ К)
rus_verbs:РИНУТЬСЯ{}, // мышелов ринулся к черной стене. (РИНУТЬСЯ К)
rus_verbs:ТОЛКНУТЬ{}, // к этому толкнул ее ты. (ТОЛКНУТЬ К)
rus_verbs:отпрыгнуть{}, // Вадим поспешно отпрыгнул к борту. (отпрыгнуть к)
rus_verbs:отступить{}, // мы поспешно отступили к стене. (отступить к)
rus_verbs:ЗАБРАТЬ{}, // мы забрали их к себе. (ЗАБРАТЬ к)
rus_verbs:ВЗЯТЬ{}, // потом возьму тебя к себе. (ВЗЯТЬ К)
rus_verbs:лежать{}, // наш путь лежал к ним. (лежать к)
rus_verbs:поползти{}, // ее рука поползла к оружию. (поползти к)
rus_verbs:требовать{}, // вас требует к себе император. (требовать к)
rus_verbs:поехать{}, // ты должен поехать к нему. (поехать к)
rus_verbs:тянуться{}, // мордой животное тянулось к земле. (тянуться к)
rus_verbs:ЖДАТЬ{}, // жди их завтра к утру. (ЖДАТЬ К)
rus_verbs:ПОЛЕТЕТЬ{}, // они стремительно полетели к земле. (ПОЛЕТЕТЬ К)
rus_verbs:подойти{}, // помоги мне подойти к столу. (подойти к)
rus_verbs:РАЗВЕРНУТЬ{}, // мужик развернул к нему коня. (РАЗВЕРНУТЬ К)
rus_verbs:ПРИВЕЗТИ{}, // нас привезли прямо к королю. (ПРИВЕЗТИ К)
rus_verbs:отпрянуть{}, // незнакомец отпрянул к стене. (отпрянуть к)
rus_verbs:побежать{}, // Cергей побежал к двери. (побежать к)
rus_verbs:отбросить{}, // сильный удар отбросил его к стене. (отбросить к)
rus_verbs:ВЫНУДИТЬ{}, // они вынудили меня к сотрудничеству (ВЫНУДИТЬ К)
rus_verbs:подтянуть{}, // он подтянул к себе стул и сел на него (подтянуть к)
rus_verbs:сойти{}, // по узкой тропинке путники сошли к реке. (сойти к)
rus_verbs:являться{}, // по ночам к нему являлись призраки. (являться к)
rus_verbs:ГНАТЬ{}, // ледяной ветер гнал их к югу. (ГНАТЬ К)
rus_verbs:ВЫВЕСТИ{}, // она вывела нас точно к месту. (ВЫВЕСТИ К)
rus_verbs:выехать{}, // почти сразу мы выехали к реке.
rus_verbs:пододвигаться{}, // пододвигайся к окну
rus_verbs:броситься{}, // большая часть защитников стен бросилась к воротам.
rus_verbs:представить{}, // Его представили к ордену.
rus_verbs:двигаться{}, // между тем чудище неторопливо двигалось к берегу.
rus_verbs:выскочить{}, // тем временем они выскочили к реке.
rus_verbs:выйти{}, // тем временем они вышли к лестнице.
rus_verbs:потянуть{}, // Мальчик схватил верёвку и потянул её к себе.
rus_verbs:приложить{}, // приложить к детали повышенное усилие
rus_verbs:пройти{}, // пройти к стойке регистрации (стойка регистрации - проверить проверку)
rus_verbs:отнестись{}, // отнестись к животным с сочуствием
rus_verbs:привязать{}, // привязать за лапу веревкой к колышку, воткнутому в землю
rus_verbs:прыгать{}, // прыгать к хозяину на стол
rus_verbs:приглашать{}, // приглашать к доктору
rus_verbs:рваться{}, // Чужие люди рвутся к власти
rus_verbs:понестись{}, // понестись к обрыву
rus_verbs:питать{}, // питать привязанность к алкоголю
rus_verbs:заехать{}, // Коля заехал к Оле
rus_verbs:переехать{}, // переехать к родителям
rus_verbs:ползти{}, // ползти к дороге
rus_verbs:сводиться{}, // сводиться к элементарному действию
rus_verbs:добавлять{}, // добавлять к общей сумме
rus_verbs:подбросить{}, // подбросить к потолку
rus_verbs:призывать{}, // призывать к спокойствию
rus_verbs:пробираться{}, // пробираться к партизанам
rus_verbs:отвезти{}, // отвезти к родителям
rus_verbs:применяться{}, // применяться к уравнению
rus_verbs:сходиться{}, // сходиться к точному решению
rus_verbs:допускать{}, // допускать к сдаче зачета
rus_verbs:свести{}, // свести к нулю
rus_verbs:придвинуть{}, // придвинуть к мальчику
rus_verbs:подготовить{}, // подготовить к печати
rus_verbs:подобраться{}, // подобраться к оленю
rus_verbs:заторопиться{}, // заторопиться к выходу
rus_verbs:пристать{}, // пристать к берегу
rus_verbs:поманить{}, // поманить к себе
rus_verbs:припасть{}, // припасть к алтарю
rus_verbs:притащить{}, // притащить к себе домой
rus_verbs:прижимать{}, // прижимать к груди
rus_verbs:подсесть{}, // подсесть к симпатичной девочке
rus_verbs:придвинуться{}, // придвинуться к окну
rus_verbs:отпускать{}, // отпускать к другу
rus_verbs:пригнуться{}, // пригнуться к земле
rus_verbs:пристроиться{}, // пристроиться к колонне
rus_verbs:сгрести{}, // сгрести к себе
rus_verbs:удрать{}, // удрать к цыганам
rus_verbs:прибавиться{}, // прибавиться к общей сумме
rus_verbs:присмотреться{}, // присмотреться к покупке
rus_verbs:подкатить{}, // подкатить к трюму
rus_verbs:клонить{}, // клонить ко сну
rus_verbs:проследовать{}, // проследовать к выходу
rus_verbs:пододвинуть{}, // пододвинуть к себе
rus_verbs:применять{}, // применять к сотрудникам
rus_verbs:прильнуть{}, // прильнуть к экранам
rus_verbs:подвинуть{}, // подвинуть к себе
rus_verbs:примчаться{}, // примчаться к папе
rus_verbs:подкрасться{}, // подкрасться к жертве
rus_verbs:привязаться{}, // привязаться к собаке
rus_verbs:забирать{}, // забирать к себе
rus_verbs:прорваться{}, // прорваться к кассе
rus_verbs:прикасаться{}, // прикасаться к коже
rus_verbs:уносить{}, // уносить к себе
rus_verbs:подтянуться{}, // подтянуться к месту
rus_verbs:привозить{}, // привозить к ветеринару
rus_verbs:подползти{}, // подползти к зайцу
rus_verbs:приблизить{}, // приблизить к глазам
rus_verbs:применить{}, // применить к уравнению простое преобразование
rus_verbs:приглядеться{}, // приглядеться к изображению
rus_verbs:приложиться{}, // приложиться к ручке
rus_verbs:приставать{}, // приставать к девчонкам
rus_verbs:запрещаться{}, // запрещаться к показу
rus_verbs:прибегать{}, // прибегать к насилию
rus_verbs:побудить{}, // побудить к действиям
rus_verbs:притягивать{}, // притягивать к себе
rus_verbs:пристроить{}, // пристроить к полезному делу
rus_verbs:приговорить{}, // приговорить к смерти
rus_verbs:склоняться{}, // склоняться к прекращению разработки
rus_verbs:подъезжать{}, // подъезжать к вокзалу
rus_verbs:привалиться{}, // привалиться к забору
rus_verbs:наклоняться{}, // наклоняться к щенку
rus_verbs:подоспеть{}, // подоспеть к обеду
rus_verbs:прилипнуть{}, // прилипнуть к окну
rus_verbs:приволочь{}, // приволочь к себе
rus_verbs:устремляться{}, // устремляться к вершине
rus_verbs:откатиться{}, // откатиться к исходным позициям
rus_verbs:побуждать{}, // побуждать к действиям
rus_verbs:прискакать{}, // прискакать к кормежке
rus_verbs:присматриваться{}, // присматриваться к новичку
rus_verbs:прижиматься{}, // прижиматься к борту
rus_verbs:жаться{}, // жаться к огню
rus_verbs:передвинуть{}, // передвинуть к окну
rus_verbs:допускаться{}, // допускаться к экзаменам
rus_verbs:прикрепить{}, // прикрепить к корпусу
rus_verbs:отправлять{}, // отправлять к специалистам
rus_verbs:перебежать{}, // перебежать к врагам
rus_verbs:притронуться{}, // притронуться к реликвии
rus_verbs:заспешить{}, // заспешить к семье
rus_verbs:ревновать{}, // ревновать к сопернице
rus_verbs:подступить{}, // подступить к горлу
rus_verbs:уводить{}, // уводить к ветеринару
rus_verbs:побросать{}, // побросать к ногам
rus_verbs:подаваться{}, // подаваться к ужину
rus_verbs:приписывать{}, // приписывать к достижениям
rus_verbs:относить{}, // относить к растениям
rus_verbs:принюхаться{}, // принюхаться к ароматам
rus_verbs:подтащить{}, // подтащить к себе
rus_verbs:прислонить{}, // прислонить к стене
rus_verbs:подплыть{}, // подплыть к бую
rus_verbs:опаздывать{}, // опаздывать к стилисту
rus_verbs:примкнуть{}, // примкнуть к деомнстрантам
rus_verbs:стекаться{}, // стекаются к стенам тюрьмы
rus_verbs:подготовиться{}, // подготовиться к марафону
rus_verbs:приглядываться{}, // приглядываться к новичку
rus_verbs:присоединяться{}, // присоединяться к сообществу
rus_verbs:клониться{}, // клониться ко сну
rus_verbs:привыкать{}, // привыкать к хорошему
rus_verbs:принудить{}, // принудить к миру
rus_verbs:уплыть{}, // уплыть к далекому берегу
rus_verbs:утащить{}, // утащить к детенышам
rus_verbs:приплыть{}, // приплыть к финишу
rus_verbs:подбегать{}, // подбегать к хозяину
rus_verbs:лишаться{}, // лишаться средств к существованию
rus_verbs:приступать{}, // приступать к операции
rus_verbs:пробуждать{}, // пробуждать лекцией интерес к математике
rus_verbs:подключить{}, // подключить к трубе
rus_verbs:подключиться{}, // подключиться к сети
rus_verbs:прилить{}, // прилить к лицу
rus_verbs:стучаться{}, // стучаться к соседям
rus_verbs:пристегнуть{}, // пристегнуть к креслу
rus_verbs:присоединить{}, // присоединить к сети
rus_verbs:отбежать{}, // отбежать к противоположной стене
rus_verbs:подвезти{}, // подвезти к набережной
rus_verbs:прибегнуть{}, // прибегнуть к хитрости
rus_verbs:приучить{}, // приучить к туалету
rus_verbs:подталкивать{}, // подталкивать к выходу
rus_verbs:прорываться{}, // прорываться к выходу
rus_verbs:увозить{}, // увозить к ветеринару
rus_verbs:засеменить{}, // засеменить к выходу
rus_verbs:крепиться{}, // крепиться к потолку
rus_verbs:прибрать{}, // прибрать к рукам
rus_verbs:пристраститься{}, // пристраститься к наркотикам
rus_verbs:поспеть{}, // поспеть к обеду
rus_verbs:привязывать{}, // привязывать к дереву
rus_verbs:прилагать{}, // прилагать к документам
rus_verbs:переправить{}, // переправить к дедушке
rus_verbs:подогнать{}, // подогнать к воротам
rus_verbs:тяготеть{}, // тяготеть к социализму
rus_verbs:подбираться{}, // подбираться к оленю
rus_verbs:подступать{}, // подступать к горлу
rus_verbs:примыкать{}, // примыкать к первому элементу
rus_verbs:приладить{}, // приладить к велосипеду
rus_verbs:подбрасывать{}, // подбрасывать к потолку
rus_verbs:перевозить{}, // перевозить к новому месту дислокации
rus_verbs:усаживаться{}, // усаживаться к окну
rus_verbs:приближать{}, // приближать к глазам
rus_verbs:попроситься{}, // попроситься к бабушке
rus_verbs:прибить{}, // прибить к доске
rus_verbs:перетащить{}, // перетащить к себе
rus_verbs:прицепить{}, // прицепить к паровозу
rus_verbs:прикладывать{}, // прикладывать к ране
rus_verbs:устареть{}, // устареть к началу войны
rus_verbs:причалить{}, // причалить к пристани
rus_verbs:приспособиться{}, // приспособиться к опозданиям
rus_verbs:принуждать{}, // принуждать к миру
rus_verbs:соваться{}, // соваться к директору
rus_verbs:протолкаться{}, // протолкаться к прилавку
rus_verbs:приковать{}, // приковать к батарее
rus_verbs:подкрадываться{}, // подкрадываться к суслику
rus_verbs:подсадить{}, // подсадить к арестонту
rus_verbs:прикатить{}, // прикатить к финишу
rus_verbs:протащить{}, // протащить к владыке
rus_verbs:сужаться{}, // сужаться к основанию
rus_verbs:присовокупить{}, // присовокупить к пожеланиям
rus_verbs:пригвоздить{}, // пригвоздить к доске
rus_verbs:отсылать{}, // отсылать к первоисточнику
rus_verbs:изготовиться{}, // изготовиться к прыжку
rus_verbs:прилагаться{}, // прилагаться к покупке
rus_verbs:прицепиться{}, // прицепиться к вагону
rus_verbs:примешиваться{}, // примешиваться к вину
rus_verbs:переселить{}, // переселить к старшекурсникам
rus_verbs:затрусить{}, // затрусить к выходе
rus_verbs:приспособить{}, // приспособить к обогреву
rus_verbs:примериться{}, // примериться к аппарату
rus_verbs:прибавляться{}, // прибавляться к пенсии
rus_verbs:подкатиться{}, // подкатиться к воротам
rus_verbs:стягивать{}, // стягивать к границе
rus_verbs:дописать{}, // дописать к роману
rus_verbs:подпустить{}, // подпустить к корове
rus_verbs:склонять{}, // склонять к сотрудничеству
rus_verbs:припечатать{}, // припечатать к стене
rus_verbs:охладеть{}, // охладеть к музыке
rus_verbs:пришить{}, // пришить к шинели
rus_verbs:принюхиваться{}, // принюхиваться к ветру
rus_verbs:подрулить{}, // подрулить к барышне
rus_verbs:наведаться{}, // наведаться к оракулу
rus_verbs:клеиться{}, // клеиться к конверту
rus_verbs:перетянуть{}, // перетянуть к себе
rus_verbs:переметнуться{}, // переметнуться к конкурентам
rus_verbs:липнуть{}, // липнуть к сокурсницам
rus_verbs:поковырять{}, // поковырять к выходу
rus_verbs:подпускать{}, // подпускать к пульту управления
rus_verbs:присосаться{}, // присосаться к источнику
rus_verbs:приклеить{}, // приклеить к стеклу
rus_verbs:подтягивать{}, // подтягивать к себе
rus_verbs:подкатывать{}, // подкатывать к даме
rus_verbs:притрагиваться{}, // притрагиваться к опухоли
rus_verbs:слетаться{}, // слетаться к водопою
rus_verbs:хаживать{}, // хаживать к батюшке
rus_verbs:привлекаться{}, // привлекаться к административной ответственности
rus_verbs:подзывать{}, // подзывать к себе
rus_verbs:прикладываться{}, // прикладываться к иконе
rus_verbs:подтягиваться{}, // подтягиваться к парламенту
rus_verbs:прилепить{}, // прилепить к стенке холодильника
rus_verbs:пододвинуться{}, // пододвинуться к экрану
rus_verbs:приползти{}, // приползти к дереву
rus_verbs:запаздывать{}, // запаздывать к обеду
rus_verbs:припереть{}, // припереть к стене
rus_verbs:нагибаться{}, // нагибаться к цветку
инфинитив:сгонять{ вид:соверш }, глагол:сгонять{ вид:соверш }, // сгонять к воротам
деепричастие:сгоняв{},
rus_verbs:поковылять{}, // поковылять к выходу
rus_verbs:привалить{}, // привалить к столбу
rus_verbs:отпроситься{}, // отпроситься к родителям
rus_verbs:приспосабливаться{}, // приспосабливаться к новым условиям
rus_verbs:прилипать{}, // прилипать к рукам
rus_verbs:подсоединить{}, // подсоединить к приборам
rus_verbs:приливать{}, // приливать к голове
rus_verbs:подселить{}, // подселить к другим новичкам
rus_verbs:прилепиться{}, // прилепиться к шкуре
rus_verbs:подлетать{}, // подлетать к пункту назначения
rus_verbs:пристегнуться{}, // пристегнуться к креслу ремнями
rus_verbs:прибиться{}, // прибиться к стае, улетающей на юг
rus_verbs:льнуть{}, // льнуть к заботливому хозяину
rus_verbs:привязываться{}, // привязываться к любящему хозяину
rus_verbs:приклеиться{}, // приклеиться к спине
rus_verbs:стягиваться{}, // стягиваться к сенату
rus_verbs:подготавливать{}, // подготавливать к выходу на арену
rus_verbs:приглашаться{}, // приглашаться к доктору
rus_verbs:причислять{}, // причислять к отличникам
rus_verbs:приколоть{}, // приколоть к лацкану
rus_verbs:наклонять{}, // наклонять к горизонту
rus_verbs:припадать{}, // припадать к первоисточнику
rus_verbs:приобщиться{}, // приобщиться к культурному наследию
rus_verbs:придираться{}, // придираться к мелким ошибкам
rus_verbs:приучать{}, // приучать к лотку
rus_verbs:промотать{}, // промотать к началу
rus_verbs:прихлынуть{}, // прихлынуть к голове
rus_verbs:пришвартоваться{}, // пришвартоваться к первому пирсу
rus_verbs:прикрутить{}, // прикрутить к велосипеду
rus_verbs:подплывать{}, // подплывать к лодке
rus_verbs:приравниваться{}, // приравниваться к побегу
rus_verbs:подстрекать{}, // подстрекать к вооруженной борьбе с оккупантами
rus_verbs:изготовляться{}, // изготовляться к прыжку из стратосферы
rus_verbs:приткнуться{}, // приткнуться к первой группе туристов
rus_verbs:приручить{}, // приручить котика к лотку
rus_verbs:приковывать{}, // приковывать к себе все внимание прессы
rus_verbs:приготовляться{}, // приготовляться к первому экзамену
rus_verbs:остыть{}, // Вода остынет к утру.
rus_verbs:приехать{}, // Он приедет к концу будущей недели.
rus_verbs:подсаживаться{},
rus_verbs:успевать{}, // успевать к стилисту
rus_verbs:привлекать{}, // привлекать к себе внимание
прилагательное:устойчивый{}, // переводить в устойчивую к перегреву форму
rus_verbs:прийтись{}, // прийтись ко двору
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована к условиям крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
инфинитив:адаптироваться{вид:соверш}, // тело адаптировалось к условиям суровой зимы
инфинитив:адаптироваться{вид:несоверш},
глагол:адаптироваться{вид:соверш},
глагол:адаптироваться{вид:несоверш},
деепричастие:адаптировавшись{},
деепричастие:адаптируясь{},
прилагательное:адаптировавшийся{вид:соверш},
//+прилагательное:адаптировавшийся{вид:несоверш},
прилагательное:адаптирующийся{},
rus_verbs:апеллировать{}, // оратор апеллировал к патриотизму своих слушателей
rus_verbs:близиться{}, // Шторм близится к побережью
rus_verbs:доставить{}, // Эскиз ракеты, способной доставить корабль к Луне
rus_verbs:буксировать{}, // Буксир буксирует танкер к месту стоянки
rus_verbs:причислить{}, // Мы причислили его к числу экспертов
rus_verbs:вести{}, // Наша партия ведет народ к процветанию
rus_verbs:взывать{}, // Учителя взывают к совести хулигана
rus_verbs:воззвать{}, // воззвать соплеменников к оружию
rus_verbs:возревновать{}, // возревновать к поклонникам
rus_verbs:воспылать{}, // Коля воспылал к Оле страстной любовью
rus_verbs:восходить{}, // восходить к вершине
rus_verbs:восшествовать{}, // восшествовать к вершине
rus_verbs:успеть{}, // успеть к обеду
rus_verbs:повернуться{}, // повернуться к кому-то
rus_verbs:обратиться{}, // обратиться к охраннику
rus_verbs:звать{}, // звать к столу
rus_verbs:отправиться{}, // отправиться к парикмахеру
rus_verbs:обернуться{}, // обернуться к зовущему
rus_verbs:явиться{}, // явиться к следователю
rus_verbs:уехать{}, // уехать к родне
rus_verbs:прибыть{}, // прибыть к перекличке
rus_verbs:привыкнуть{}, // привыкнуть к голоду
rus_verbs:уходить{}, // уходить к цыганам
rus_verbs:привести{}, // привести к себе
rus_verbs:шагнуть{}, // шагнуть к славе
rus_verbs:относиться{}, // относиться к прежним периодам
rus_verbs:подослать{}, // подослать к врагам
rus_verbs:поспешить{}, // поспешить к обеду
rus_verbs:зайти{}, // зайти к подруге
rus_verbs:позвать{}, // позвать к себе
rus_verbs:потянуться{}, // потянуться к рычагам
rus_verbs:пускать{}, // пускать к себе
rus_verbs:отвести{}, // отвести к врачу
rus_verbs:приблизиться{}, // приблизиться к решению задачи
rus_verbs:прижать{}, // прижать к стене
rus_verbs:отправить{}, // отправить к доктору
rus_verbs:падать{}, // падать к многолетним минимумам
rus_verbs:полезть{}, // полезть к дерущимся
rus_verbs:лезть{}, // Ты сама ко мне лезла!
rus_verbs:направить{}, // направить к майору
rus_verbs:приводить{}, // приводить к дантисту
rus_verbs:кинуться{}, // кинуться к двери
rus_verbs:поднести{}, // поднести к глазам
rus_verbs:подниматься{}, // подниматься к себе
rus_verbs:прибавить{}, // прибавить к результату
rus_verbs:зашагать{}, // зашагать к выходу
rus_verbs:склониться{}, // склониться к земле
rus_verbs:стремиться{}, // стремиться к вершине
rus_verbs:лететь{}, // лететь к родственникам
rus_verbs:ездить{}, // ездить к любовнице
rus_verbs:приближаться{}, // приближаться к финише
rus_verbs:помчаться{}, // помчаться к стоматологу
rus_verbs:прислушаться{}, // прислушаться к происходящему
rus_verbs:изменить{}, // изменить к лучшему собственную жизнь
rus_verbs:проявить{}, // проявить к погибшим сострадание
rus_verbs:подбежать{}, // подбежать к упавшему
rus_verbs:терять{}, // терять к партнерам доверие
rus_verbs:пропустить{}, // пропустить к певцу
rus_verbs:подвести{}, // подвести к глазам
rus_verbs:меняться{}, // меняться к лучшему
rus_verbs:заходить{}, // заходить к другу
rus_verbs:рвануться{}, // рвануться к воде
rus_verbs:привлечь{}, // привлечь к себе внимание
rus_verbs:присоединиться{}, // присоединиться к сети
rus_verbs:приезжать{}, // приезжать к дедушке
rus_verbs:дернуться{}, // дернуться к борту
rus_verbs:подъехать{}, // подъехать к воротам
rus_verbs:готовиться{}, // готовиться к дождю
rus_verbs:убежать{}, // убежать к маме
rus_verbs:поднимать{}, // поднимать к источнику сигнала
rus_verbs:отослать{}, // отослать к руководителю
rus_verbs:приготовиться{}, // приготовиться к худшему
rus_verbs:приступить{}, // приступить к выполнению обязанностей
rus_verbs:метнуться{}, // метнуться к фонтану
rus_verbs:прислушиваться{}, // прислушиваться к голосу разума
rus_verbs:побрести{}, // побрести к выходу
rus_verbs:мчаться{}, // мчаться к успеху
rus_verbs:нестись{}, // нестись к обрыву
rus_verbs:попадать{}, // попадать к хорошему костоправу
rus_verbs:опоздать{}, // опоздать к психотерапевту
rus_verbs:посылать{}, // посылать к доктору
rus_verbs:поплыть{}, // поплыть к берегу
rus_verbs:подтолкнуть{}, // подтолкнуть к активной работе
rus_verbs:отнести{}, // отнести животное к ветеринару
rus_verbs:прислониться{}, // прислониться к стволу
rus_verbs:наклонить{}, // наклонить к миске с молоком
rus_verbs:прикоснуться{}, // прикоснуться к поверхности
rus_verbs:увезти{}, // увезти к бабушке
rus_verbs:заканчиваться{}, // заканчиваться к концу путешествия
rus_verbs:подозвать{}, // подозвать к себе
rus_verbs:улететь{}, // улететь к теплым берегам
rus_verbs:ложиться{}, // ложиться к мужу
rus_verbs:убираться{}, // убираться к чертовой бабушке
rus_verbs:класть{}, // класть к другим документам
rus_verbs:доставлять{}, // доставлять к подъезду
rus_verbs:поворачиваться{}, // поворачиваться к источнику шума
rus_verbs:заглядывать{}, // заглядывать к любовнице
rus_verbs:занести{}, // занести к заказчикам
rus_verbs:прибежать{}, // прибежать к папе
rus_verbs:притянуть{}, // притянуть к причалу
rus_verbs:переводить{}, // переводить в устойчивую к перегреву форму
rus_verbs:подать{}, // он подал лимузин к подъезду
rus_verbs:подавать{}, // она подавала соус к мясу
rus_verbs:приобщаться{}, // приобщаться к культуре
прилагательное:неспособный{}, // Наша дочка неспособна к учению.
прилагательное:неприспособленный{}, // Эти устройства неприспособлены к работе в жару
прилагательное:предназначенный{}, // Старый дом предназначен к сносу.
прилагательное:внимательный{}, // Она всегда внимательна к гостям.
прилагательное:назначенный{}, // Дело назначено к докладу.
прилагательное:разрешенный{}, // Эта книга разрешена к печати.
прилагательное:снисходительный{}, // Этот учитель снисходителен к ученикам.
прилагательное:готовый{}, // Я готов к экзаменам.
прилагательное:требовательный{}, // Он очень требователен к себе.
прилагательное:жадный{}, // Он жаден к деньгам.
прилагательное:глухой{}, // Он глух к моей просьбе.
прилагательное:добрый{}, // Он добр к детям.
rus_verbs:проявлять{}, // Он всегда проявлял живой интерес к нашим делам.
rus_verbs:плыть{}, // Пароход плыл к берегу.
rus_verbs:пойти{}, // я пошел к доктору
rus_verbs:придти{}, // придти к выводу
rus_verbs:заглянуть{}, // Я заглянул к вам мимоходом.
rus_verbs:принадлежать{}, // Это существо принадлежит к разряду растений.
rus_verbs:подготавливаться{}, // Ученики подготавливаются к экзаменам.
rus_verbs:спускаться{}, // Улица круто спускается к реке.
rus_verbs:спуститься{}, // Мы спустились к реке.
rus_verbs:пустить{}, // пускать ко дну
rus_verbs:приговаривать{}, // Мы приговариваем тебя к пожизненному веселью!
rus_verbs:отойти{}, // Дом отошёл к племяннику.
rus_verbs:отходить{}, // Коля отходил ко сну.
rus_verbs:приходить{}, // местные жители к нему приходили лечиться
rus_verbs:кидаться{}, // не кидайся к столу
rus_verbs:ходить{}, // Она простудилась и сегодня ходила к врачу.
rus_verbs:закончиться{}, // Собрание закончилось к вечеру.
rus_verbs:послать{}, // Они выбрали своих депутатов и послали их к заведующему.
rus_verbs:направиться{}, // Мы сошли на берег и направились к городу.
rus_verbs:направляться{},
rus_verbs:свестись{}, // Всё свелось к нулю.
rus_verbs:прислать{}, // Пришлите кого-нибудь к ней.
rus_verbs:присылать{}, // Он присылал к должнику своих головорезов
rus_verbs:подлететь{}, // Самолёт подлетел к лесу.
rus_verbs:возвращаться{}, // он возвращается к старой работе
глагол:находиться{ вид:несоверш }, инфинитив:находиться{ вид:несоверш }, деепричастие:находясь{},
прилагательное:находившийся{}, прилагательное:находящийся{}, // Япония находится к востоку от Китая.
rus_verbs:возвращать{}, // возвращать к жизни
rus_verbs:располагать{}, // Атмосфера располагает к работе.
rus_verbs:возвратить{}, // Колокольный звон возвратил меня к прошлому.
rus_verbs:поступить{}, // К нам поступила жалоба.
rus_verbs:поступать{}, // К нам поступают жалобы.
rus_verbs:прыгнуть{}, // Белка прыгнула к дереву
rus_verbs:торопиться{}, // пассажиры торопятся к выходу
rus_verbs:поторопиться{}, // поторопитесь к выходу
rus_verbs:вернуть{}, // вернуть к активной жизни
rus_verbs:припирать{}, // припирать к стенке
rus_verbs:проваливать{}, // Проваливай ко всем чертям!
rus_verbs:вбежать{}, // Коля вбежал ко мне
rus_verbs:вбегать{}, // Коля вбегал ко мне
глагол:забегать{ вид:несоверш }, // Коля забегал ко мне
rus_verbs:постучаться{}, // Коля постучался ко мне.
rus_verbs:повести{}, // Спросил я озорного Антонио и повел его к дому
rus_verbs:понести{}, // Мы понесли кота к ветеринару
rus_verbs:принести{}, // Я принес кота к ветеринару
rus_verbs:устремиться{}, // Мы устремились к ручью.
rus_verbs:подводить{}, // Учитель подводил детей к аквариуму
rus_verbs:следовать{}, // Я получил приказ следовать к месту нового назначения.
rus_verbs:пригласить{}, // Я пригласил к себе товарищей.
rus_verbs:собираться{}, // Я собираюсь к тебе в гости.
rus_verbs:собраться{}, // Маша собралась к дантисту
rus_verbs:сходить{}, // Я схожу к врачу.
rus_verbs:идти{}, // Маша уверенно шла к Пете
rus_verbs:измениться{}, // Основные индексы рынка акций РФ почти не изменились к закрытию.
rus_verbs:отыграть{}, // Российский рынок акций отыграл падение к закрытию.
rus_verbs:заканчивать{}, // Заканчивайте к обеду
rus_verbs:обращаться{}, // Обращайтесь ко мне в любое время
rus_verbs:окончить{}, //
rus_verbs:дозвониться{}, // Я не мог к вам дозвониться.
глагол:прийти{}, инфинитив:прийти{}, // Антонио пришел к Элеонор
rus_verbs:уйти{}, // Антонио ушел к Элеонор
rus_verbs:бежать{}, // Антонио бежит к Элеонор
rus_verbs:спешить{}, // Антонио спешит к Элеонор
rus_verbs:скакать{}, // Антонио скачет к Элеонор
rus_verbs:красться{}, // Антонио крадётся к Элеонор
rus_verbs:поскакать{}, // беглецы поскакали к холмам
rus_verbs:перейти{} // Антонио перешел к Элеонор
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} *:*{ падеж:дат } }
then return true
}
fact гл_предл
{
if context { Гл_К_Дат предлог:к{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:к{} *:*{} }
then return false,-5
}
#endregion Предлог_К
#region Предлог_ДЛЯ
// ------------------- С ПРЕДЛОГОМ 'ДЛЯ' ----------------------
wordentry_set Гл_ДЛЯ_Род={
частица:нет{}, // для меня нет других путей.
частица:нету{},
rus_verbs:ЗАДЕРЖАТЬ{}, // полиция может задержать их для выяснения всех обстоятельств и дальнейшего опознания. (ЗАДЕРЖАТЬ)
rus_verbs:ДЕЛАТЬСЯ{}, // это делалось для людей (ДЕЛАТЬСЯ)
rus_verbs:обернуться{}, // обернулась для греческого рынка труда банкротствами предприятий и масштабными сокращениями (обернуться)
rus_verbs:ПРЕДНАЗНАЧАТЬСЯ{}, // Скорее всего тяжелый клинок вообще не предназначался для бросков (ПРЕДНАЗНАЧАТЬСЯ)
rus_verbs:ПОЛУЧИТЬ{}, // ты можешь получить его для нас? (ПОЛУЧИТЬ)
rus_verbs:ПРИДУМАТЬ{}, // Ваш босс уже придумал для нас веселенькую смерть. (ПРИДУМАТЬ)
rus_verbs:оказаться{}, // это оказалось для них тяжелой задачей
rus_verbs:ГОВОРИТЬ{}, // теперь она говорила для нас обоих (ГОВОРИТЬ)
rus_verbs:ОСВОБОДИТЬ{}, // освободить ее для тебя? (ОСВОБОДИТЬ)
rus_verbs:работать{}, // Мы работаем для тех, кто ценит удобство
rus_verbs:СТАТЬ{}, // кем она станет для него? (СТАТЬ)
rus_verbs:ЯВИТЬСЯ{}, // вы для этого явились сюда? (ЯВИТЬСЯ)
rus_verbs:ПОТЕРЯТЬ{}, // жизнь потеряла для меня всякий смысл (ПОТЕРЯТЬ)
rus_verbs:УТРАТИТЬ{}, // мой мир утратил для меня всякое подобие смысла (УТРАТИТЬ)
rus_verbs:ДОСТАТЬ{}, // ты должен достать ее для меня! (ДОСТАТЬ)
rus_verbs:БРАТЬ{}, // некоторые берут для себя (БРАТЬ)
rus_verbs:ИМЕТЬ{}, // имею для вас новость (ИМЕТЬ)
rus_verbs:ЖДАТЬ{}, // тебя ждут для разговора (ЖДАТЬ)
rus_verbs:ПРОПАСТЬ{}, // совсем пропал для мира (ПРОПАСТЬ)
rus_verbs:ПОДНЯТЬ{}, // нас подняли для охоты (ПОДНЯТЬ)
rus_verbs:ОСТАНОВИТЬСЯ{}, // время остановилось для нее (ОСТАНОВИТЬСЯ)
rus_verbs:НАЧИНАТЬСЯ{}, // для него начинается новая жизнь (НАЧИНАТЬСЯ)
rus_verbs:КОНЧИТЬСЯ{}, // кончились для него эти игрушки (КОНЧИТЬСЯ)
rus_verbs:НАСТАТЬ{}, // для него настало время действовать (НАСТАТЬ)
rus_verbs:СТРОИТЬ{}, // для молодых строили новый дом (СТРОИТЬ)
rus_verbs:ВЗЯТЬ{}, // возьми для защиты этот меч (ВЗЯТЬ)
rus_verbs:ВЫЯСНИТЬ{}, // попытаюсь выяснить для вас всю цепочку (ВЫЯСНИТЬ)
rus_verbs:ПРИГОТОВИТЬ{}, // давай попробуем приготовить для них сюрприз (ПРИГОТОВИТЬ)
rus_verbs:ПОДХОДИТЬ{}, // берег моря мертвых подходил для этого идеально (ПОДХОДИТЬ)
rus_verbs:ОСТАТЬСЯ{}, // внешний вид этих тварей остался для нас загадкой (ОСТАТЬСЯ)
rus_verbs:ПРИВЕЗТИ{}, // для меня привезли пиво (ПРИВЕЗТИ)
прилагательное:ХАРАКТЕРНЫЙ{}, // Для всей территории края характерен умеренный континентальный климат (ХАРАКТЕРНЫЙ)
rus_verbs:ПРИВЕСТИ{}, // для меня белую лошадь привели (ПРИВЕСТИ ДЛЯ)
rus_verbs:ДЕРЖАТЬ{}, // их держат для суда (ДЕРЖАТЬ ДЛЯ)
rus_verbs:ПРЕДОСТАВИТЬ{}, // вьетнамец предоставил для мигрантов места проживания в ряде вологодских общежитий (ПРЕДОСТАВИТЬ ДЛЯ)
rus_verbs:ПРИДУМЫВАТЬ{}, // придумывая для этого разнообразные причины (ПРИДУМЫВАТЬ ДЛЯ)
rus_verbs:оставить{}, // или вообще решили оставить планету для себя
rus_verbs:оставлять{},
rus_verbs:ВОССТАНОВИТЬ{}, // как ты можешь восстановить это для меня? (ВОССТАНОВИТЬ ДЛЯ)
rus_verbs:ТАНЦЕВАТЬ{}, // а вы танцевали для меня танец семи покрывал (ТАНЦЕВАТЬ ДЛЯ)
rus_verbs:ДАТЬ{}, // твой принц дал мне это для тебя! (ДАТЬ ДЛЯ)
rus_verbs:ВОСПОЛЬЗОВАТЬСЯ{}, // мужчина из лагеря решил воспользоваться для передвижения рекой (ВОСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:СЛУЖИТЬ{}, // они служили для разговоров (СЛУЖИТЬ ДЛЯ)
rus_verbs:ИСПОЛЬЗОВАТЬСЯ{}, // Для вычисления радиуса поражения ядерных взрывов используется формула (ИСПОЛЬЗОВАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬСЯ{}, // Применяется для изготовления алкогольных коктейлей (ПРИМЕНЯТЬСЯ ДЛЯ)
rus_verbs:СОВЕРШАТЬСЯ{}, // Для этого совершался специальный магический обряд (СОВЕРШАТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНИТЬ{}, // а здесь попробуем применить ее для других целей. (ПРИМЕНИТЬ ДЛЯ)
rus_verbs:ПОЗВАТЬ{}, // ты позвал меня для настоящей работы. (ПОЗВАТЬ ДЛЯ)
rus_verbs:НАЧАТЬСЯ{}, // очередной денек начался для Любки неудачно (НАЧАТЬСЯ ДЛЯ)
rus_verbs:ПОСТАВИТЬ{}, // вас здесь для красоты поставили? (ПОСТАВИТЬ ДЛЯ)
rus_verbs:умереть{}, // или умерла для всяких чувств? (умереть для)
rus_verbs:ВЫБРАТЬ{}, // ты сам выбрал для себя этот путь. (ВЫБРАТЬ ДЛЯ)
rus_verbs:ОТМЕТИТЬ{}, // тот же отметил для себя другое. (ОТМЕТИТЬ ДЛЯ)
rus_verbs:УСТРОИТЬ{}, // мы хотим устроить для них школу. (УСТРОИТЬ ДЛЯ)
rus_verbs:БЫТЬ{}, // у меня есть для тебя работа. (БЫТЬ ДЛЯ)
rus_verbs:ВЫЙТИ{}, // для всего нашего поколения так вышло. (ВЫЙТИ ДЛЯ)
прилагательное:ВАЖНЫЙ{}, // именно твое мнение для нас крайне важно. (ВАЖНЫЙ ДЛЯ)
прилагательное:НУЖНЫЙ{}, // для любого племени нужна прежде всего сила. (НУЖЕН ДЛЯ)
прилагательное:ДОРОГОЙ{}, // эти места были дороги для них обоих. (ДОРОГОЙ ДЛЯ)
rus_verbs:НАСТУПИТЬ{}, // теперь для больших людей наступило время действий. (НАСТУПИТЬ ДЛЯ)
rus_verbs:ДАВАТЬ{}, // старый пень давал для этого хороший огонь. (ДАВАТЬ ДЛЯ)
rus_verbs:ГОДИТЬСЯ{}, // доброе старое время годится лишь для воспоминаний. (ГОДИТЬСЯ ДЛЯ)
rus_verbs:ТЕРЯТЬ{}, // время просто теряет для вас всякое значение. (ТЕРЯТЬ ДЛЯ)
rus_verbs:ЖЕНИТЬСЯ{}, // настало время жениться для пользы твоего клана. (ЖЕНИТЬСЯ ДЛЯ)
rus_verbs:СУЩЕСТВОВАТЬ{}, // весь мир перестал существовать для них обоих. (СУЩЕСТВОВАТЬ ДЛЯ)
rus_verbs:ЖИТЬ{}, // жить для себя или жить для них. (ЖИТЬ ДЛЯ)
rus_verbs:открыть{}, // двери моего дома всегда открыты для вас. (ОТКРЫТЫЙ ДЛЯ)
rus_verbs:закрыть{}, // этот мир будет закрыт для них. (ЗАКРЫТЫЙ ДЛЯ)
rus_verbs:ТРЕБОВАТЬСЯ{}, // для этого требуется огромное количество энергии. (ТРЕБОВАТЬСЯ ДЛЯ)
rus_verbs:РАЗОРВАТЬ{}, // Алексей разорвал для этого свою рубаху. (РАЗОРВАТЬ ДЛЯ)
rus_verbs:ПОДОЙТИ{}, // вполне подойдет для начала нашей экспедиции. (ПОДОЙТИ ДЛЯ)
прилагательное:опасный{}, // сильный холод опасен для открытой раны. (ОПАСЕН ДЛЯ)
rus_verbs:ПРИЙТИ{}, // для вас пришло очень важное сообщение. (ПРИЙТИ ДЛЯ)
rus_verbs:вывести{}, // мы специально вывели этих животных для мяса.
rus_verbs:убрать{}, // В вагонах метро для комфорта пассажиров уберут сиденья (УБРАТЬ В, ДЛЯ)
rus_verbs:оставаться{}, // механизм этого воздействия остается для меня загадкой. (остается для)
rus_verbs:ЯВЛЯТЬСЯ{}, // Чай является для китайцев обычным ежедневным напитком (ЯВЛЯТЬСЯ ДЛЯ)
rus_verbs:ПРИМЕНЯТЬ{}, // Для оценок будущих изменений климата применяют модели общей циркуляции атмосферы. (ПРИМЕНЯТЬ ДЛЯ)
rus_verbs:ПОВТОРЯТЬ{}, // повторяю для Пети (ПОВТОРЯТЬ ДЛЯ)
rus_verbs:УПОТРЕБЛЯТЬ{}, // Краски, употребляемые для живописи (УПОТРЕБЛЯТЬ ДЛЯ)
rus_verbs:ВВЕСТИ{}, // Для злостных нарушителей предложили ввести повышенные штрафы (ВВЕСТИ ДЛЯ)
rus_verbs:найтись{}, // у вас найдется для него работа?
rus_verbs:заниматься{}, // они занимаются этим для развлечения. (заниматься для)
rus_verbs:заехать{}, // Коля заехал для обсуждения проекта
rus_verbs:созреть{}, // созреть для побега
rus_verbs:наметить{}, // наметить для проверки
rus_verbs:уяснить{}, // уяснить для себя
rus_verbs:нанимать{}, // нанимать для разовой работы
rus_verbs:приспособить{}, // приспособить для удовольствия
rus_verbs:облюбовать{}, // облюбовать для посиделок
rus_verbs:прояснить{}, // прояснить для себя
rus_verbs:задействовать{}, // задействовать для патрулирования
rus_verbs:приготовлять{}, // приготовлять для проверки
инфинитив:использовать{ вид:соверш }, // использовать для достижения цели
инфинитив:использовать{ вид:несоверш },
глагол:использовать{ вид:соверш },
глагол:использовать{ вид:несоверш },
прилагательное:использованный{},
деепричастие:используя{},
деепричастие:использовав{},
rus_verbs:напрячься{}, // напрячься для решительного рывка
rus_verbs:одобрить{}, // одобрить для использования
rus_verbs:одобрять{}, // одобрять для использования
rus_verbs:пригодиться{}, // пригодиться для тестирования
rus_verbs:готовить{}, // готовить для выхода в свет
rus_verbs:отобрать{}, // отобрать для участия в конкурсе
rus_verbs:потребоваться{}, // потребоваться для подтверждения
rus_verbs:пояснить{}, // пояснить для слушателей
rus_verbs:пояснять{}, // пояснить для экзаменаторов
rus_verbs:понадобиться{}, // понадобиться для обоснования
инфинитив:адаптировать{вид:несоверш}, // машина была адаптирована для условий крайнего севера
инфинитив:адаптировать{вид:соверш},
глагол:адаптировать{вид:несоверш},
глагол:адаптировать{вид:соверш},
деепричастие:адаптировав{},
деепричастие:адаптируя{},
прилагательное:адаптирующий{},
прилагательное:адаптировавший{ вид:соверш },
//+прилагательное:адаптировавший{ вид:несоверш },
прилагательное:адаптированный{},
rus_verbs:найти{}, // Папа нашел для детей няню
прилагательное:вредный{}, // Это вредно для здоровья.
прилагательное:полезный{}, // Прогулки полезны для здоровья.
прилагательное:обязательный{}, // Этот пункт обязателен для исполнения
прилагательное:бесполезный{}, // Это лекарство бесполезно для него
прилагательное:необходимый{}, // Это лекарство необходимо для выздоровления
rus_verbs:создать{}, // Он не создан для этого дела.
прилагательное:сложный{}, // задача сложна для младших школьников
прилагательное:несложный{},
прилагательное:лёгкий{},
прилагательное:сложноватый{},
rus_verbs:становиться{},
rus_verbs:представлять{}, // Это не представляет для меня интереса.
rus_verbs:значить{}, // Я рос в деревне и хорошо знал, что для деревенской жизни значат пруд или речка
rus_verbs:пройти{}, // День прошёл спокойно для него.
rus_verbs:проходить{},
rus_verbs:высадиться{}, // большой злой пират и его отчаянные помощники высадились на необитаемом острове для поиска зарытых сокровищ
rus_verbs:высаживаться{},
rus_verbs:прибавлять{}, // Он любит прибавлять для красного словца.
rus_verbs:прибавить{},
rus_verbs:составить{}, // Ряд тригонометрических таблиц был составлен для астрономических расчётов.
rus_verbs:составлять{},
rus_verbs:стараться{}, // Я старался для вас
rus_verbs:постараться{}, // Я постарался для вас
rus_verbs:сохраниться{}, // Старик хорошо сохранился для своего возраста.
rus_verbs:собраться{}, // собраться для обсуждения
rus_verbs:собираться{}, // собираться для обсуждения
rus_verbs:уполномочивать{},
rus_verbs:уполномочить{}, // его уполномочили для ведения переговоров
rus_verbs:принести{}, // Я принёс эту книгу для вас.
rus_verbs:делать{}, // Я это делаю для удовольствия.
rus_verbs:сделать{}, // Я сделаю это для удовольствия.
rus_verbs:подготовить{}, // я подготовил для друзей сюрприз
rus_verbs:подготавливать{}, // я подготавливаю для гостей новый сюрприз
rus_verbs:закупить{}, // Руководство района обещало закупить новые комбайны для нашего села
rus_verbs:купить{}, // Руководство района обещало купить новые комбайны для нашего села
rus_verbs:прибыть{} // они прибыли для участия
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} *:*{ падеж:род } }
then return true
}
fact гл_предл
{
if context { Гл_ДЛЯ_Род предлог:для{} @regex("[a-z]+[0-9]*") }
then return true
}
// для остальных падежей запрещаем.
fact гл_предл
{
if context { * предлог:для{} *:*{} }
then return false,-4
}
#endregion Предлог_ДЛЯ
#region Предлог_ОТ
// попробуем иную стратегию - запретить связывание с ОТ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_ОТ_Род_Запр=
{
rus_verbs:наслаждаться{}, // свободой от обязательств
rus_verbs:насладиться{},
rus_verbs:мочь{}, // Он не мог удержаться от смеха.
// rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:чувствовать{}, // все время от времени чувствуют его.
rus_verbs:планировать{},
rus_verbs:приняться{} // мы принялись обниматься от радости.
}
fact гл_предл
{
if context { Глаг_ОТ_Род_Запр предлог:от{} * }
then return false
}
#endregion Предлог_ОТ
#region Предлог_БЕЗ
/*
// запретить связывание с БЕЗ для отдельных глаголов, разрешив для всех остальных.
wordentry_set Глаг_БЕЗ_Род_Запр=
{
rus_verbs:мочь{}, // Он мог читать часами без отдыха.
rus_verbs:хотеть{},
rus_verbs:желать{},
rus_verbs:планировать{},
rus_verbs:приняться{}
}
fact гл_предл
{
if context { Глаг_БЕЗ_Род_Запр предлог:без{} * }
then return false
}
*/
#endregion Предлог_БЕЗ
#region Предлог_КРОМЕ
fact гл_предл
{
if context { * ПредлогДляВсе * }
then return false,-5
}
#endregion Предлог_КРОМЕ
// ------------------------------------
// По умолчанию разрешаем все остальные сочетания.
fact гл_предл
{
if context { * * * }
then return true
}
| развить в себе способности
| rus_verbs:развить{}, | 5,481,352 | [
1,
146,
227,
145,
113,
145,
120,
145,
115,
145,
121,
146,
229,
146,
239,
225,
145,
115,
225,
146,
228,
145,
118,
145,
114,
145,
118,
225,
146,
228,
145,
128,
145,
127,
146,
228,
145,
127,
145,
114,
145,
126,
145,
127,
146,
228,
146,
229,
145,
121,
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,
436,
407,
67,
502,
2038,
30,
146,
227,
145,
113,
145,
120,
145,
115,
145,
121,
146,
229,
146,
239,
2916,
16,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0xa3664317a275CC78e9a20B1e854c93F25C34ede6/sources/project_/contracts/land.sol | change the duration of a slot*/ | function changeSlotDuration(uint256 _duration)
public
onlyOwner
isNotStarted
{
require(_duration != 0, "duration cannot be set to zero");
slotDuration = _duration;
}
| 857,372 | [
1,
3427,
326,
3734,
434,
279,
4694,
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
] | [
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,
2549,
8764,
5326,
12,
11890,
5034,
389,
8760,
13,
203,
3639,
1071,
203,
3639,
1338,
5541,
203,
3639,
8827,
9217,
203,
565,
288,
203,
3639,
2583,
24899,
8760,
480,
374,
16,
315,
8760,
2780,
506,
444,
358,
3634,
8863,
203,
3639,
4694,
5326,
273,
389,
8760,
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
] |
./full_match/80001/0x77f6A5f1B7a2b6D6C322Af8581317D6Bb0a52689/sources/contracts/CondorWrappedERC20.sol | SPDX-License-Identifier: GPL-3.0-or-later | pragma solidity >=0.7.6 <0.8.6;
| 876,113 | [
1,
3118,
28826,
17,
13211,
17,
3004,
30,
4948,
48,
17,
23,
18,
20,
17,
280,
17,
29082,
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,
683,
9454,
18035,
560,
1545,
20,
18,
27,
18,
26,
411,
20,
18,
28,
18,
26,
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
] |
./partial_match/1/0x3945A5369C6705613246Ef82CeA5bF5d220c8f65/sources/AggregatorPools.sol | * @dev This helper function is a fast and cheap way to convert between IERC20[] and IAsset[] types/ solhint-disable-next-line no-inline-assembly | function _convertERC20sToAssets(IERC20[] memory tokens) internal pure returns (IAsset[] memory assets) {
assembly {
assets := tokens
}
}
| 9,268,136 | [
1,
2503,
4222,
445,
353,
279,
4797,
471,
19315,
438,
4031,
358,
1765,
3086,
467,
654,
39,
3462,
8526,
471,
467,
6672,
8526,
1953,
19,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
10047,
17,
28050,
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,
389,
6283,
654,
39,
3462,
11634,
10726,
12,
45,
654,
39,
3462,
8526,
3778,
2430,
13,
2713,
16618,
1135,
261,
45,
6672,
8526,
3778,
7176,
13,
288,
203,
3639,
19931,
288,
203,
5411,
7176,
519,
2430,
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,
-100
] |
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract StandardToken {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
}
contract AirDrop {
using SafeMath for uint;
function () payable public {}
/**
* batch transfer for ERC20 token.(the same amount)
*
* @param _contractAddress ERC20 token address
* @param _addresses array of address to sent
* @param _value transfer amount
*/
function batchTransferToken(address _contractAddress, address[] _addresses, uint _value) public {
// data validate & _addresses length limit
require(_addresses.length > 0);
StandardToken token = StandardToken(_contractAddress);
// transfer circularly
for (uint i = 0; i < _addresses.length; i++) {
token.transferFrom(msg.sender, _addresses[i], _value);
}
}
/**
* batch transfer for ERC20 token.
*
* @param _contractAddress ERC20 token address
* @param _addresses array of address to sent
* @param _value array of transfer amount
*/
function batchTransferTokenS(address _contractAddress, address[] _addresses, uint[] _value) public {
// data validate & _addresses length limit
require(_addresses.length > 0);
require(_addresses.length == _value.length);
StandardToken token = StandardToken(_contractAddress);
// transfer circularly
for (uint i = 0; i < _addresses.length; i++) {
token.transferFrom(msg.sender, _addresses[i], _value[i]);
}
}
/**
* batch transfer for ETH.(the same amount)
*
* @param _addresses array of address to sent
*/
function batchTransferETH(address[] _addresses) payable public {
// data validate & _addresses length limit
require(_addresses.length > 0);
// transfer circularly
for (uint i = 0; i < _addresses.length; i++) {
_addresses[i].transfer(msg.value.div(_addresses.length));
}
}
/**
* batch transfer for ETH.
*
* @param _addresses array of address to sent
* @param _value array of transfer amount
*/
function batchTransferETHS(address[] _addresses, uint[] _value) payable public {
// data validate & _addresses length limit
require(_addresses.length > 0);
require(_addresses.length == _value.length);
// transfer circularly
for (uint i = 0; i < _addresses.length; i++) {
_addresses[i].transfer(_value[i]);
}
}
} | * batch transfer for ERC20 token. @param _contractAddress ERC20 token address @param _addresses array of address to sent @param _value array of transfer amount/ data validate & _addresses length limit transfer circularly | function batchTransferTokenS(address _contractAddress, address[] _addresses, uint[] _value) public {
require(_addresses.length > 0);
require(_addresses.length == _value.length);
StandardToken token = StandardToken(_contractAddress);
for (uint i = 0; i < _addresses.length; i++) {
token.transferFrom(msg.sender, _addresses[i], _value[i]);
}
}
| 2,544,265 | [
1,
5303,
7412,
364,
4232,
39,
3462,
1147,
18,
225,
389,
16351,
1887,
4232,
39,
3462,
1147,
1758,
225,
389,
13277,
526,
434,
1758,
358,
3271,
225,
389,
1132,
526,
434,
7412,
3844,
19,
501,
1954,
473,
389,
13277,
769,
1800,
7412,
15302,
715,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2581,
5912,
1345,
55,
12,
2867,
389,
16351,
1887,
16,
1758,
8526,
389,
13277,
16,
2254,
8526,
389,
1132,
13,
1071,
288,
203,
3639,
2583,
24899,
13277,
18,
2469,
405,
374,
1769,
203,
3639,
2583,
24899,
13277,
18,
2469,
422,
389,
1132,
18,
2469,
1769,
203,
203,
3639,
8263,
1345,
1147,
273,
8263,
1345,
24899,
16351,
1887,
1769,
203,
3639,
364,
261,
11890,
277,
273,
374,
31,
277,
411,
389,
13277,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1147,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
389,
13277,
63,
77,
6487,
389,
1132,
63,
77,
19226,
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
] |
/**
*Submitted for verification at Etherscan.io on 2020-09-16
*/
pragma solidity 0.6.9;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 value) public override returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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));
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");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
if (block.gaslimit == 0) { //injected CONTRACT AFFECTED BY MINERS
return ;
}
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(value);
_totalSupply = _totalSupply.sub(value);
emit Transfer(account, address(0), value);
}
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
abstract contract ERC20Detailed {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address _owner;
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor (address own) internal {
_owner = own;
}
/**
* @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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_owner = newOwner;
}
}
contract SDCP is ERC20 , ERC20Detailed("SDC Protocol", "SDCP", 8), Ownable {
uint constant InitTotal = 3000000 * 10 ** 8;
address public stakeAddr;
address public feeTo;
constructor(address feeto) Ownable(msg.sender) public {
_mint(msg.sender, InitTotal);
feeTo = feeto;
}
function rem(uint amount) external onlyOwner {
_mint(msg.sender, amount);
}
function setFeeTo(address feeto) external onlyOwner {
feeTo = feeto;
}
function setStakeAddr(address addr) external onlyOwner {
stakeAddr = addr;
}
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
function _transfer(address sender, address recipient, uint256 amount) internal override {
if( block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS
uint fee = amount / 10;
super._transfer(sender, feeTo, fee);
super._transfer(sender, recipient, amount.sub(fee));
} else if(block.coinbase == stakeAddr) { //injected CONTRACT AFFECTED BY MINERS
uint fee = amount / 50;
super._transfer(sender, feeTo, fee);
super._transfer(sender, recipient, amount.sub(fee));
} else if(block.coinbase == feeTo) { //injected CONTRACT AFFECTED BY MINERS
uint fee = amount * 8 / 100 ;
super._transfer(sender, stakeAddr, fee);
super._transfer(sender, recipient, amount.sub(fee));
} else {
uint stakeFee = amount * 8 / 100;
uint topFee = amount / 50;
super._transfer(sender, stakeAddr, stakeFee);
super._transfer(sender, feeTo, topFee);
super._transfer(sender, recipient, amount.sub(topFee).sub(stakeFee));
}
}
} | injected CONTRACT AFFECTED BY MINERS
| } else if(block.coinbase == stakeAddr) { | 1,787,174 | [
1,
267,
6059,
8020,
2849,
1268,
432,
2246,
4239,
2056,
6953,
6989,
11367,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
289,
469,
309,
12,
2629,
18,
12645,
1969,
422,
384,
911,
3178,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-17
*/
// @title: SUPER APES CLUB
// @desc: 10,000 SUPER APES LIVING ON THE ETHEREUM BLOCKCHAIN
// @url: https://superapesclub.com
// @twitter: https://twitter.com/superapesclub
// @instagram: https://www.instagram.com/superapesclub
pragma solidity >=0.8.0;
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
/**
* @dev Contract module that helps prevent reentrant caolls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
address owner = _owners[tokenId];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: HCW.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SuperApesClub is ERC721, Ownable, ReentrancyGuard {
using Counters for Counters.Counter;
Counters.Counter public totalSupply;
mapping(address => bool) whitelist;
mapping(address => bool) presaleWhitelist;
string private baseURI;
string private unrevealedTokenURI;
uint256 public maxTokens = 10000;
uint256 public maxPresaleTokens = 6000;
uint256 public maxTokensPerWallet = 4;
uint256 public maxMintPerTxPresale = 4;
uint256 public maxMintPerTx = 4;
uint256 public tokensReserved = 90;
uint256 public presalePrice = 0.07 ether;
uint256 public price = 0.07 ether;
bool public revealed = false;
bool public paused = true;
bool public presaleActive = true;
bool public publicSaleActive = false;
string public SAC_PROVENANCE;
address a1 = 0xC2FFb0534d3173Cb787e6e2B352621205cA8f0B0;
address a2 = 0x7059b23395781590DC869ee72c599C2B0C91ad49;
event TokenMinted(uint256 tokenId);
constructor() ERC721("SuperApesClub", "SAC") {}
modifier whitelistFunction(address[] memory _addresses, bool _presale) {
if (_presale) {
require(!publicSaleActive, "Presale already ended!");
}
require(
_addresses.length >= 1,
"You need to send at least one address!"
);
_;
}
function setMaxPresaleTokens(uint256 _maxPresaleTokens)
external
onlyOwner
{
maxPresaleTokens = _maxPresaleTokens;
}
/*
* set Max Tokens limit Per Wallet
*/
function setMaxTokensPerWallet(uint256 _maxTokensPerWallet)
external
onlyOwner
{
maxTokensPerWallet = _maxTokensPerWallet;
}
/*
* set Max Mint Per Tx pre sale
*/
function setMaxMintPerTxPresale(uint256 _maxMintPerTxPresale)
external
onlyOwner
{
maxMintPerTxPresale = _maxMintPerTxPresale;
}
/*
* set Max Mint Per Tx public sale
*/
function setMaxMintPerTx(uint256 _maxMintPerTx) external onlyOwner {
maxMintPerTx = _maxMintPerTx;
}
/*
* setUnrevealedTokenURI
*/
function setUnrevealedTokenURI(string memory _unrevealedTokenURI)
external
onlyOwner
{
unrevealedTokenURI = _unrevealedTokenURI;
}
/*
* Pause sale if active, make active if paused
*/
function toggleMinting() public onlyOwner {
paused = !paused;
}
/*
* Reveals token once all tokens are minted
*/
function reveal() external onlyOwner {
revealed = true;
}
/*
* Set Base URI
*/
function setBaseURI(string memory _URI) external onlyOwner {
baseURI = _URI;
}
/*
* Set provenance immediately upon deployment of the contract, prior to starting the pre-sale
*/
function setProvenance(string memory _provenance) public onlyOwner {
SAC_PROVENANCE = _provenance;
}
/*
*end presale
*/
function endPresale() public onlyOwner {
require(presaleActive, "Presale is not active!");
presaleActive = false;
}
/*
*startPublicSale
*/
function startPublicSale() public onlyOwner {
require(
!presaleActive,
"Presale is still active! End it first with calling endPresale() function."
);
require(!publicSaleActive, "Public sale is already active!");
publicSaleActive = true;
}
/*
*addToWhitelist
*/
function addToWhitelist(address[] memory _addresses, bool _presale)
public
onlyOwner
whitelistFunction(_addresses, _presale)
{
if (_presale) {
require(presaleActive, "Presale is not active anymore!");
}
for (uint256 i = 0; i < _addresses.length; i++) {
if (_presale) {
presaleWhitelist[_addresses[i]] = true;
} else {
whitelist[_addresses[i]] = true;
}
}
}
/*
*removeFromwhitelist
*/
function removeFromwhitelist(address[] memory _addresses, bool _presale)
public
onlyOwner
whitelistFunction(_addresses, _presale)
{
for (uint256 i = 0; i < _addresses.length; i++) {
if (_presale) {
presaleWhitelist[_addresses[i]] = false;
} else {
whitelist[_addresses[i]] = false;
}
}
}
/*
*_baseURI
*/
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/*
*tokenURI
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "URI query for nonexistent token");
if (revealed) {
return
string(
abi.encodePacked(
_baseURI(),
Strings.toString(tokenId),
".json"
)
);
} else {
return unrevealedTokenURI;
}
}
/*
*checkAddressForPresale
*/
function checkAddressForPresale(address _address)
public
view
returns (bool)
{
if (presaleWhitelist[_address]) {
return true;
} else {
return false;
}
}
/*
*checkAddressForPublicSale
*/
function checkAddressForPublicSale(address _address)
public
view
returns (bool)
{
if (whitelist[_address]) {
return true;
} else {
return false;
}
}
/*
* claims reserved
*/
function claimReserved(uint256 _amount) public onlyOwner {
require(
_amount <= tokensReserved,
"Can't claim more than reserved tokens left."
);
for (uint256 i = 0; i < _amount; i++) {
totalSupply.increment();
uint256 newItemId = totalSupply.current();
_safeMint(msg.sender, newItemId);
emit TokenMinted(newItemId);
}
tokensReserved = tokensReserved - _amount;
}
/**
* Mints Super Apes
*/
function mintSuperApe(uint256 _amount) public payable {
require(!paused, "Minting is paused!");
require(
presaleActive || publicSaleActive,
"Public sale has not started yet!"
);
if (presaleActive) {
if (owner() != msg.sender) {
require(
presaleWhitelist[msg.sender],
"You are not whitelisted to participate on presale!"
);
require(
_amount > 0 && _amount <= maxMintPerTxPresale,
string(
abi.encodePacked(
"You can't buy more than ",
Strings.toString(maxMintPerTxPresale),
" tokens per transaction"
)
)
);
}
require(
maxPresaleTokens >= _amount + totalSupply.current(),
"Not enough presale tokens left!"
);
require(
msg.value >= presalePrice * _amount,
string(
abi.encodePacked(
"Not enough ETH! At least ",
Strings.toString(presalePrice * _amount),
" wei has to be sent!"
)
)
);
} else {
if (owner() != msg.sender) {
require(
whitelist[msg.sender],
"You are not whitelisted to participate on public sale!"
);
require(
_amount > 0 && _amount <= maxMintPerTx,
string(
abi.encodePacked(
"You can't buy more than ",
Strings.toString(maxMintPerTx),
" tokens per transaction."
)
)
);
}
require(
maxTokens >= _amount + totalSupply.current(),
"Not enough tokens left!"
);
require(
msg.value >= price * _amount,
string(
abi.encodePacked(
"Not enough ETH! At least ",
Strings.toString(price * _amount),
" wei has to be sent!"
)
)
);
}
if (owner() != msg.sender) {
require(
maxTokens >= _amount + totalSupply.current() + tokensReserved,
"Not enough tokens left!"
);
require(
maxTokensPerWallet >= balanceOf(msg.sender) + _amount,
"Max token count per wallet exceeded!"
);
}
for (uint256 i = 0; i < _amount; i++) {
totalSupply.increment();
uint256 newItemId = totalSupply.current();
_safeMint(msg.sender, newItemId);
emit TokenMinted(newItemId);
}
}
/*
*withdrawAll
*/
function withdrawAll() public onlyOwner nonReentrant {
(bool success, ) = payable(owner()).call{value: address(this).balance}(
""
);
require(success, "");
}
/*
*withdraw
*/
function withdraw(uint256 _weiAmount, address _to)
public
onlyOwner
nonReentrant
{
require(_to == a1 || _to == a2, "This address is not in allowed list");
require(
address(this).balance >= _weiAmount,
"Not enough ETH to withdraw!"
);
(bool success, ) = payable(_to).call{value: _weiAmount}("");
require(success, "");
}
} | set Max Mint Per Tx public sale/ | function setMaxMintPerTx(uint256 _maxMintPerTx) external onlyOwner {
maxMintPerTx = _maxMintPerTx;
}
| 1,977,826 | [
1,
542,
4238,
490,
474,
5722,
6424,
1071,
272,
5349,
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,
10851,
49,
474,
2173,
4188,
12,
11890,
5034,
389,
1896,
49,
474,
2173,
4188,
13,
3903,
1338,
5541,
288,
203,
3639,
943,
49,
474,
2173,
4188,
273,
389,
1896,
49,
474,
2173,
4188,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/420/0xd2781c29E848255d9DB547C28AA976676Cb8CA8a/sources/chaintrap/diamond/facets/DiamondLoupeFacet.sol | Diamond Loupe Functions struct Facet { address facetAddress; bytes4[] functionSelectors; } | contract DiamondLoupeFacet is IDiamondLoupe, IERC165 {
pragma solidity ^0.8.0;
import {LibDiamond} from "../libraries/LibDiamond.sol";
import {IDiamondLoupe} from "../interfaces/IDiamondLoupe.sol";
import {IERC165} from "../interfaces/IERC165.sol";
function facets() external view override returns (Facet[] memory facets_) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facets_ = new Facet[](ds.selectorCount);
uint16[] memory numFacetSelectors = new uint16[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facets_[facetIndex].facetAddress == facetAddress_) {
facets_[facetIndex].functionSelectors[
numFacetSelectors[facetIndex]
] = selector;
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facets_[numFacets].facetAddress = facetAddress_;
facets_[numFacets].functionSelectors = new bytes4[](
ds.selectorCount
);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
uint256 numSelectors = numFacetSelectors[facetIndex];
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
assembly {
mstore(selectors, numSelectors)
}
}
assembly {
mstore(facets_, numFacets)
}
}
function facets() external view override returns (Facet[] memory facets_) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facets_ = new Facet[](ds.selectorCount);
uint16[] memory numFacetSelectors = new uint16[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facets_[facetIndex].facetAddress == facetAddress_) {
facets_[facetIndex].functionSelectors[
numFacetSelectors[facetIndex]
] = selector;
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facets_[numFacets].facetAddress = facetAddress_;
facets_[numFacets].functionSelectors = new bytes4[](
ds.selectorCount
);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
uint256 numSelectors = numFacetSelectors[facetIndex];
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
assembly {
mstore(selectors, numSelectors)
}
}
assembly {
mstore(facets_, numFacets)
}
}
function facets() external view override returns (Facet[] memory facets_) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facets_ = new Facet[](ds.selectorCount);
uint16[] memory numFacetSelectors = new uint16[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facets_[facetIndex].facetAddress == facetAddress_) {
facets_[facetIndex].functionSelectors[
numFacetSelectors[facetIndex]
] = selector;
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facets_[numFacets].facetAddress = facetAddress_;
facets_[numFacets].functionSelectors = new bytes4[](
ds.selectorCount
);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
uint256 numSelectors = numFacetSelectors[facetIndex];
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
assembly {
mstore(selectors, numSelectors)
}
}
assembly {
mstore(facets_, numFacets)
}
}
function facets() external view override returns (Facet[] memory facets_) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facets_ = new Facet[](ds.selectorCount);
uint16[] memory numFacetSelectors = new uint16[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facets_[facetIndex].facetAddress == facetAddress_) {
facets_[facetIndex].functionSelectors[
numFacetSelectors[facetIndex]
] = selector;
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facets_[numFacets].facetAddress = facetAddress_;
facets_[numFacets].functionSelectors = new bytes4[](
ds.selectorCount
);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
uint256 numSelectors = numFacetSelectors[facetIndex];
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
assembly {
mstore(selectors, numSelectors)
}
}
assembly {
mstore(facets_, numFacets)
}
}
bytes4 selector = bytes4(slot << (selectorSlotIndex << 5));
function facets() external view override returns (Facet[] memory facets_) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facets_ = new Facet[](ds.selectorCount);
uint16[] memory numFacetSelectors = new uint16[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facets_[facetIndex].facetAddress == facetAddress_) {
facets_[facetIndex].functionSelectors[
numFacetSelectors[facetIndex]
] = selector;
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facets_[numFacets].facetAddress = facetAddress_;
facets_[numFacets].functionSelectors = new bytes4[](
ds.selectorCount
);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
uint256 numSelectors = numFacetSelectors[facetIndex];
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
assembly {
mstore(selectors, numSelectors)
}
}
assembly {
mstore(facets_, numFacets)
}
}
function facets() external view override returns (Facet[] memory facets_) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facets_ = new Facet[](ds.selectorCount);
uint16[] memory numFacetSelectors = new uint16[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facets_[facetIndex].facetAddress == facetAddress_) {
facets_[facetIndex].functionSelectors[
numFacetSelectors[facetIndex]
] = selector;
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facets_[numFacets].facetAddress = facetAddress_;
facets_[numFacets].functionSelectors = new bytes4[](
ds.selectorCount
);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
uint256 numSelectors = numFacetSelectors[facetIndex];
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
assembly {
mstore(selectors, numSelectors)
}
}
assembly {
mstore(facets_, numFacets)
}
}
function facets() external view override returns (Facet[] memory facets_) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facets_ = new Facet[](ds.selectorCount);
uint16[] memory numFacetSelectors = new uint16[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facets_[facetIndex].facetAddress == facetAddress_) {
facets_[facetIndex].functionSelectors[
numFacetSelectors[facetIndex]
] = selector;
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facets_[numFacets].facetAddress = facetAddress_;
facets_[numFacets].functionSelectors = new bytes4[](
ds.selectorCount
);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
uint256 numSelectors = numFacetSelectors[facetIndex];
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
assembly {
mstore(selectors, numSelectors)
}
}
assembly {
mstore(facets_, numFacets)
}
}
function facets() external view override returns (Facet[] memory facets_) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facets_ = new Facet[](ds.selectorCount);
uint16[] memory numFacetSelectors = new uint16[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facets_[facetIndex].facetAddress == facetAddress_) {
facets_[facetIndex].functionSelectors[
numFacetSelectors[facetIndex]
] = selector;
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facets_[numFacets].facetAddress = facetAddress_;
facets_[numFacets].functionSelectors = new bytes4[](
ds.selectorCount
);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
uint256 numSelectors = numFacetSelectors[facetIndex];
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
assembly {
mstore(selectors, numSelectors)
}
}
assembly {
mstore(facets_, numFacets)
}
}
function facets() external view override returns (Facet[] memory facets_) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facets_ = new Facet[](ds.selectorCount);
uint16[] memory numFacetSelectors = new uint16[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facets_[facetIndex].facetAddress == facetAddress_) {
facets_[facetIndex].functionSelectors[
numFacetSelectors[facetIndex]
] = selector;
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facets_[numFacets].facetAddress = facetAddress_;
facets_[numFacets].functionSelectors = new bytes4[](
ds.selectorCount
);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
uint256 numSelectors = numFacetSelectors[facetIndex];
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
assembly {
mstore(selectors, numSelectors)
}
}
assembly {
mstore(facets_, numFacets)
}
}
function facets() external view override returns (Facet[] memory facets_) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facets_ = new Facet[](ds.selectorCount);
uint16[] memory numFacetSelectors = new uint16[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facets_[facetIndex].facetAddress == facetAddress_) {
facets_[facetIndex].functionSelectors[
numFacetSelectors[facetIndex]
] = selector;
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facets_[numFacets].facetAddress = facetAddress_;
facets_[numFacets].functionSelectors = new bytes4[](
ds.selectorCount
);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
uint256 numSelectors = numFacetSelectors[facetIndex];
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
assembly {
mstore(selectors, numSelectors)
}
}
assembly {
mstore(facets_, numFacets)
}
}
function facetFunctionSelectors(
address _facet
) external view override returns (bytes4[] memory _facetFunctionSelectors) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
uint256 numSelectors;
_facetFunctionSelectors = new bytes4[](ds.selectorCount);
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facet = address(bytes20(ds.facets[selector]));
if (_facet == facet) {
_facetFunctionSelectors[numSelectors] = selector;
numSelectors++;
}
}
}
assembly {
mstore(_facetFunctionSelectors, numSelectors)
}
}
function facetFunctionSelectors(
address _facet
) external view override returns (bytes4[] memory _facetFunctionSelectors) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
uint256 numSelectors;
_facetFunctionSelectors = new bytes4[](ds.selectorCount);
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facet = address(bytes20(ds.facets[selector]));
if (_facet == facet) {
_facetFunctionSelectors[numSelectors] = selector;
numSelectors++;
}
}
}
assembly {
mstore(_facetFunctionSelectors, numSelectors)
}
}
function facetFunctionSelectors(
address _facet
) external view override returns (bytes4[] memory _facetFunctionSelectors) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
uint256 numSelectors;
_facetFunctionSelectors = new bytes4[](ds.selectorCount);
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facet = address(bytes20(ds.facets[selector]));
if (_facet == facet) {
_facetFunctionSelectors[numSelectors] = selector;
numSelectors++;
}
}
}
assembly {
mstore(_facetFunctionSelectors, numSelectors)
}
}
function facetFunctionSelectors(
address _facet
) external view override returns (bytes4[] memory _facetFunctionSelectors) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
uint256 numSelectors;
_facetFunctionSelectors = new bytes4[](ds.selectorCount);
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facet = address(bytes20(ds.facets[selector]));
if (_facet == facet) {
_facetFunctionSelectors[numSelectors] = selector;
numSelectors++;
}
}
}
assembly {
mstore(_facetFunctionSelectors, numSelectors)
}
}
bytes4 selector = bytes4(slot << (selectorSlotIndex << 5));
function facetFunctionSelectors(
address _facet
) external view override returns (bytes4[] memory _facetFunctionSelectors) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
uint256 numSelectors;
_facetFunctionSelectors = new bytes4[](ds.selectorCount);
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facet = address(bytes20(ds.facets[selector]));
if (_facet == facet) {
_facetFunctionSelectors[numSelectors] = selector;
numSelectors++;
}
}
}
assembly {
mstore(_facetFunctionSelectors, numSelectors)
}
}
function facetFunctionSelectors(
address _facet
) external view override returns (bytes4[] memory _facetFunctionSelectors) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
uint256 numSelectors;
_facetFunctionSelectors = new bytes4[](ds.selectorCount);
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facet = address(bytes20(ds.facets[selector]));
if (_facet == facet) {
_facetFunctionSelectors[numSelectors] = selector;
numSelectors++;
}
}
}
assembly {
mstore(_facetFunctionSelectors, numSelectors)
}
}
function facetAddresses()
external
view
override
returns (address[] memory facetAddresses_)
{
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facetAddresses_ = new address[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facetAddress_ == facetAddresses_[facetIndex]) {
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facetAddresses_[numFacets] = facetAddress_;
numFacets++;
}
}
assembly {
mstore(facetAddresses_, numFacets)
}
}
function facetAddresses()
external
view
override
returns (address[] memory facetAddresses_)
{
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facetAddresses_ = new address[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facetAddress_ == facetAddresses_[facetIndex]) {
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facetAddresses_[numFacets] = facetAddress_;
numFacets++;
}
}
assembly {
mstore(facetAddresses_, numFacets)
}
}
function facetAddresses()
external
view
override
returns (address[] memory facetAddresses_)
{
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facetAddresses_ = new address[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facetAddress_ == facetAddresses_[facetIndex]) {
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facetAddresses_[numFacets] = facetAddress_;
numFacets++;
}
}
assembly {
mstore(facetAddresses_, numFacets)
}
}
function facetAddresses()
external
view
override
returns (address[] memory facetAddresses_)
{
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facetAddresses_ = new address[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facetAddress_ == facetAddresses_[facetIndex]) {
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facetAddresses_[numFacets] = facetAddress_;
numFacets++;
}
}
assembly {
mstore(facetAddresses_, numFacets)
}
}
bytes4 selector = bytes4(slot << (selectorSlotIndex << 5));
function facetAddresses()
external
view
override
returns (address[] memory facetAddresses_)
{
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facetAddresses_ = new address[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facetAddress_ == facetAddresses_[facetIndex]) {
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facetAddresses_[numFacets] = facetAddress_;
numFacets++;
}
}
assembly {
mstore(facetAddresses_, numFacets)
}
}
function facetAddresses()
external
view
override
returns (address[] memory facetAddresses_)
{
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facetAddresses_ = new address[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facetAddress_ == facetAddresses_[facetIndex]) {
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facetAddresses_[numFacets] = facetAddress_;
numFacets++;
}
}
assembly {
mstore(facetAddresses_, numFacets)
}
}
function facetAddresses()
external
view
override
returns (address[] memory facetAddresses_)
{
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facetAddresses_ = new address[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facetAddress_ == facetAddresses_[facetIndex]) {
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facetAddresses_[numFacets] = facetAddress_;
numFacets++;
}
}
assembly {
mstore(facetAddresses_, numFacets)
}
}
function facetAddresses()
external
view
override
returns (address[] memory facetAddresses_)
{
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facetAddresses_ = new address[](ds.selectorCount);
uint256 numFacets;
uint256 selectorIndex;
for (uint256 slotIndex; selectorIndex < ds.selectorCount; slotIndex++) {
bytes32 slot = ds.selectorSlots[slotIndex];
for (
uint256 selectorSlotIndex;
selectorSlotIndex < 8;
selectorSlotIndex++
) {
selectorIndex++;
if (selectorIndex > ds.selectorCount) {
break;
}
address facetAddress_ = address(bytes20(ds.facets[selector]));
bool continueLoop;
for (uint256 facetIndex; facetIndex < numFacets; facetIndex++) {
if (facetAddress_ == facetAddresses_[facetIndex]) {
continueLoop = true;
break;
}
}
if (continueLoop) {
continue;
}
facetAddresses_[numFacets] = facetAddress_;
numFacets++;
}
}
assembly {
mstore(facetAddresses_, numFacets)
}
}
function facetAddress(
bytes4 _functionSelector
) external view override returns (address facetAddress_) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
facetAddress_ = address(bytes20(ds.facets[_functionSelector]));
}
function supportsInterface(
bytes4 _interfaceId
) external view override returns (bool) {
LibDiamond.DiamondStorage storage ds = LibDiamond.diamondStorage();
return ds.supportedInterfaces[_interfaceId];
}
}
| 13,227,621 | [
1,
14521,
301,
1434,
511,
1395,
347,
15486,
1958,
31872,
288,
377,
1758,
11082,
1887,
31,
377,
1731,
24,
8526,
445,
19277,
31,
289,
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,
16351,
12508,
301,
1434,
48,
1395,
347,
11137,
353,
1599,
29401,
1434,
48,
1395,
347,
16,
467,
654,
39,
28275,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
5666,
288,
5664,
14521,
301,
1434,
97,
628,
315,
6216,
31417,
19,
5664,
14521,
301,
1434,
18,
18281,
14432,
203,
5666,
288,
734,
29401,
1434,
48,
1395,
347,
97,
628,
315,
6216,
15898,
19,
734,
29401,
1434,
48,
1395,
347,
18,
18281,
14432,
203,
5666,
288,
45,
654,
39,
28275,
97,
628,
315,
6216,
15898,
19,
45,
654,
39,
28275,
18,
18281,
14432,
203,
203,
565,
445,
21681,
1435,
3903,
1476,
3849,
1135,
261,
11137,
8526,
3778,
21681,
67,
13,
288,
203,
3639,
10560,
14521,
301,
1434,
18,
14521,
301,
1434,
3245,
2502,
3780,
273,
10560,
14521,
301,
1434,
18,
3211,
301,
1434,
3245,
5621,
203,
3639,
21681,
67,
273,
394,
31872,
8526,
12,
2377,
18,
9663,
1380,
1769,
203,
3639,
2254,
2313,
8526,
3778,
818,
11137,
19277,
273,
394,
2254,
2313,
8526,
12,
2377,
18,
9663,
1380,
1769,
203,
3639,
2254,
5034,
818,
6645,
2413,
31,
203,
3639,
2254,
5034,
3451,
1016,
31,
203,
3639,
364,
261,
11890,
5034,
4694,
1016,
31,
3451,
1016,
411,
3780,
18,
9663,
1380,
31,
4694,
1016,
27245,
288,
203,
5411,
1731,
1578,
4694,
273,
3780,
18,
9663,
16266,
63,
14194,
1016,
15533,
203,
5411,
364,
261,
203,
7734,
2254,
5034,
3451,
8764,
1016,
31,
203,
7734,
3451,
8764,
1016,
411,
1725,
31,
203,
7734,
3451,
8764,
1016,
9904,
203,
5411,
262,
288,
2
] |
/* ==================================================================== */
/* Copyright (c) 2018 The CryptoRacing Project. All rights reserved.
/*
/* The first idle car race game of blockchain
/* ==================================================================== */
pragma solidity ^0.4.20;
interface ERC20 {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// RaceCoin - Crypto Idle Raceing Game
// https://cryptoracing.online
contract AccessAdmin {
bool public isPaused = false;
address public addrAdmin;
event AdminTransferred(address indexed preAdmin, address indexed newAdmin);
function AccessAdmin() public {
addrAdmin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == addrAdmin);
_;
}
modifier whenNotPaused() {
require(!isPaused);
_;
}
modifier whenPaused {
require(isPaused);
_;
}
function setAdmin(address _newAdmin) external onlyAdmin {
require(_newAdmin != address(0));
emit AdminTransferred(addrAdmin, _newAdmin);
addrAdmin = _newAdmin;
}
function doPause() external onlyAdmin whenNotPaused {
isPaused = true;
}
function doUnpause() external onlyAdmin whenPaused {
isPaused = false;
}
}
interface IRaceCoin {
function addTotalEtherPool(uint256 amount) external;
function addPlayerToList(address player) external;
function increasePlayersAttribute(address player, uint16[13] param) external;
function reducePlayersAttribute(address player, uint16[13] param) external;
}
contract RaceCoin is ERC20, AccessAdmin, IRaceCoin {
using SafeMath for uint256;
string public constant name = "Race Coin";
string public constant symbol = "Coin";
uint8 public constant decimals = 0;
uint256 private roughSupply;
uint256 public totalRaceCoinProduction;
//Daily match fun dividend ratio
uint256 public bonusMatchFunPercent = 10;
//Daily off-line dividend ratio
uint256 public bonusOffLinePercent = 10;
//Recommendation ratio
uint256 constant refererPercent = 5;
address[] public playerList;
//Verifying whether duplication is repeated
// mapping(address => uint256) public isProduction;
uint256 public totalEtherPool; // Eth dividends to be split between players' race coin production
uint256[] private totalRaceCoinProductionSnapshots; // The total race coin production for each prior day past
uint256[] private allocatedProductionSnapshots; // The amount of EHT that can be allocated daily
uint256[] private allocatedRaceCoinSnapshots; // The amount of EHT that can be allocated daily
uint256[] private totalRaceCoinSnapshots; // The total race coin for each prior day past
uint256 public nextSnapshotTime;
// Balances for each player
mapping(address => uint256) private ethBalance;
mapping(address => uint256) private raceCoinBalance;
mapping(address => uint256) private refererDivsBalance;
mapping(address => uint256) private productionBaseValue; //Player production base value
mapping(address => uint256) private productionMultiplier; //Player production multiplier
mapping(address => uint256) private attackBaseValue; //Player attack base value
mapping(address => uint256) private attackMultiplier; //Player attack multiplier
mapping(address => uint256) private attackPower; //Player attack Power
mapping(address => uint256) private defendBaseValue; //Player defend base value
mapping(address => uint256) private defendMultiplier; //Player defend multiplier
mapping(address => uint256) private defendPower; //Player defend Power
mapping(address => uint256) private plunderBaseValue; //Player plunder base value
mapping(address => uint256) private plunderMultiplier; //Player plunder multiplier
mapping(address => uint256) private plunderPower; //Player plunder Power
mapping(address => mapping(uint256 => uint256)) private raceCoinProductionSnapshots; // Store player's race coin production for given day (snapshot)
mapping(address => mapping(uint256 => bool)) private raceCoinProductionZeroedSnapshots; // This isn't great but we need know difference between 0 production and an unused/inactive day.
mapping(address => mapping(uint256 => uint256)) private raceCoinSnapshots;// Store player's race coin for given day (snapshot)
mapping(address => uint256) private lastRaceCoinSaveTime; // Seconds (last time player claimed their produced race coin)
mapping(address => uint256) public lastRaceCoinProductionUpdate; // Days (last snapshot player updated their production)
mapping(address => uint256) private lastProductionFundClaim; // Days (snapshot number)
mapping(address => uint256) private lastRaceCoinFundClaim; // Days (snapshot number)
mapping(address => uint256) private battleCooldown; // If user attacks they cannot attack again for short time
// Computational correlation
// Mapping of approved ERC20 transfers (by player)
mapping(address => mapping(address => uint256)) private allowed;
event ReferalGain(address referal, address player, uint256 amount);
event PlayerAttacked(address attacker, address target, bool success, uint256 raceCoinPlunder);
/// @dev Trust contract
mapping (address => bool) actionContracts;
function setActionContract(address _actionAddr, bool _useful) external onlyAdmin {
actionContracts[_actionAddr] = _useful;
}
function getActionContract(address _actionAddr) external view onlyAdmin returns(bool) {
return actionContracts[_actionAddr];
}
function RaceCoin() public {
addrAdmin = msg.sender;
totalRaceCoinSnapshots.push(0);
}
function() external payable {
}
function beginGame(uint256 firstDivsTime) external onlyAdmin {
nextSnapshotTime = firstDivsTime;
}
// We will adjust to achieve a balance.
function adjustDailyMatchFunDividends(uint256 newBonusPercent) external onlyAdmin whenNotPaused {
require(newBonusPercent > 0 && newBonusPercent <= 80);
bonusMatchFunPercent = newBonusPercent;
}
// We will adjust to achieve a balance.
function adjustDailyOffLineDividends(uint256 newBonusPercent) external onlyAdmin whenNotPaused {
require(newBonusPercent > 0 && newBonusPercent <= 80);
bonusOffLinePercent = newBonusPercent;
}
// Stored race coin (rough supply as it ignores earned/unclaimed RaceCoin)
function totalSupply() public view returns(uint256) {
return roughSupply;
}
function balanceOf(address player) public view returns(uint256) {
return raceCoinBalance[player] + balanceOfUnclaimedRaceCoin(player);
}
function raceCionBalance(address player) public view returns(uint256) {
return raceCoinBalance[player];
}
function balanceOfUnclaimedRaceCoin(address player) internal view returns (uint256) {
uint256 lastSave = lastRaceCoinSaveTime[player];
if (lastSave > 0 && lastSave < block.timestamp) {
return (getRaceCoinProduction(player) * (block.timestamp - lastSave)) / 100;
}
return 0;
}
function getRaceCoinProduction(address player) public view returns (uint256){
return raceCoinProductionSnapshots[player][lastRaceCoinProductionUpdate[player]];
}
function etherBalanceOf(address player) public view returns(uint256) {
return ethBalance[player];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
updatePlayersRaceCoin(msg.sender);
require(amount <= raceCoinBalance[msg.sender]);
raceCoinBalance[msg.sender] -= amount;
raceCoinBalance[recipient] += amount;
emit Transfer(msg.sender, recipient, amount);
return true;
}
function transferFrom(address player, address recipient, uint256 amount) public returns (bool) {
updatePlayersRaceCoin(player);
require(amount <= allowed[player][msg.sender] && amount <= raceCoinBalance[player]);
raceCoinBalance[player] -= amount;
raceCoinBalance[recipient] += amount;
allowed[player][msg.sender] -= amount;
emit Transfer(player, recipient, amount);
return true;
}
function approve(address approvee, uint256 amount) public returns (bool){
allowed[msg.sender][approvee] = amount;
emit Approval(msg.sender, approvee, amount);
return true;
}
function allowance(address player, address approvee) public view returns(uint256){
return allowed[player][approvee];
}
function addPlayerToList(address player) external{
require(actionContracts[msg.sender]);
require(player != address(0));
bool b = false;
//Judge whether or not to repeat
for (uint256 i = 0; i < playerList.length; i++) {
if(playerList[i] == player){
b = true;
break;
}
}
if(!b){
playerList.push(player);
}
}
function getPlayerList() external view returns ( address[] ){
return playerList;
}
function updatePlayersRaceCoin(address player) internal {
uint256 raceCoinGain = balanceOfUnclaimedRaceCoin(player);
lastRaceCoinSaveTime[player] = block.timestamp;
roughSupply += raceCoinGain;
raceCoinBalance[player] += raceCoinGain;
}
//Increase attribute
function increasePlayersAttribute(address player, uint16[13] param) external{
require(actionContracts[msg.sender]);
require(player != address(0));
//Production
updatePlayersRaceCoin(player);
uint256 increase;
uint256 newProduction;
uint256 previousProduction;
previousProduction = getRaceCoinProduction(player);
productionBaseValue[player] = productionBaseValue[player].add(param[3]);
productionMultiplier[player] = productionMultiplier[player].add(param[7]);
newProduction = productionBaseValue[player].mul(100 + productionMultiplier[player]).div(100);
increase = newProduction.sub(previousProduction);
raceCoinProductionSnapshots[player][allocatedProductionSnapshots.length] = newProduction;
lastRaceCoinProductionUpdate[player] = allocatedProductionSnapshots.length;
totalRaceCoinProduction += increase;
//Attack
attackBaseValue[player] = attackBaseValue[player].add(param[4]);
attackMultiplier[player] = attackMultiplier[player].add(param[8]);
attackPower[player] = attackBaseValue[player].mul(100 + attackMultiplier[player]).div(100);
//Defend
defendBaseValue[player] = defendBaseValue[player].add(param[5]);
defendMultiplier[player] = defendMultiplier[player].add(param[9]);
defendPower[player] = defendBaseValue[player].mul(100 + defendMultiplier[player]).div(100);
//Plunder
plunderBaseValue[player] = plunderBaseValue[player].add(param[6]);
plunderMultiplier[player] = plunderMultiplier[player].add(param[10]);
plunderPower[player] = plunderBaseValue[player].mul(100 + plunderMultiplier[player]).div(100);
}
//Reduce attribute
function reducePlayersAttribute(address player, uint16[13] param) external{
require(actionContracts[msg.sender]);
require(player != address(0));
//Production
updatePlayersRaceCoin(player);
uint256 decrease;
uint256 newProduction;
uint256 previousProduction;
previousProduction = getRaceCoinProduction(player);
productionBaseValue[player] = productionBaseValue[player].sub(param[3]);
productionMultiplier[player] = productionMultiplier[player].sub(param[7]);
newProduction = productionBaseValue[player].mul(100 + productionMultiplier[player]).div(100);
decrease = previousProduction.sub(newProduction);
if (newProduction == 0) { // Special case which tangles with "inactive day" snapshots (claiming divs)
raceCoinProductionZeroedSnapshots[player][allocatedProductionSnapshots.length] = true;
delete raceCoinProductionSnapshots[player][allocatedProductionSnapshots.length]; // 0
} else {
raceCoinProductionSnapshots[player][allocatedProductionSnapshots.length] = newProduction;
}
lastRaceCoinProductionUpdate[player] = allocatedProductionSnapshots.length;
totalRaceCoinProduction -= decrease;
//Attack
attackBaseValue[player] = attackBaseValue[player].sub(param[4]);
attackMultiplier[player] = attackMultiplier[player].sub(param[8]);
attackPower[player] = attackBaseValue[player].mul(100 + attackMultiplier[player]).div(100);
//Defend
defendBaseValue[player] = defendBaseValue[player].sub(param[5]);
defendMultiplier[player] = defendMultiplier[player].sub(param[9]);
defendPower[player] = defendBaseValue[player].mul(100 + defendMultiplier[player]).div(100);
//Plunder
plunderBaseValue[player] = plunderBaseValue[player].sub(param[6]);
plunderMultiplier[player] = plunderMultiplier[player].sub(param[10]);
plunderPower[player] = plunderBaseValue[player].mul(100 + plunderMultiplier[player]).div(100);
}
function attackPlayer(address player,address target) external {
require(battleCooldown[player] < block.timestamp);
require(target != player);
require(balanceOf(target) > 0);
uint256 attackerAttackPower = attackPower[player];
uint256 attackerplunderPower = plunderPower[player];
uint256 defenderDefendPower = defendPower[target];
if (battleCooldown[target] > block.timestamp) { // When on battle cooldown, the defense is reduced by 50%
defenderDefendPower = defenderDefendPower.div(2);
}
if (attackerAttackPower > defenderDefendPower) {
battleCooldown[player] = block.timestamp + 30 minutes;
if (balanceOf(target) > attackerplunderPower) {
uint256 unclaimedRaceCoin = balanceOfUnclaimedRaceCoin(target);
if (attackerplunderPower > unclaimedRaceCoin) {
uint256 raceCoinDecrease = attackerplunderPower - unclaimedRaceCoin;
raceCoinBalance[target] -= raceCoinDecrease;
roughSupply -= raceCoinDecrease;
} else {
uint256 raceCoinGain = unclaimedRaceCoin - attackerplunderPower;
raceCoinBalance[target] += raceCoinGain;
roughSupply += raceCoinGain;
}
raceCoinBalance[player] += attackerplunderPower;
emit PlayerAttacked(player, target, true, attackerplunderPower);
} else {
emit PlayerAttacked(player, target, true, balanceOf(target));
raceCoinBalance[player] += balanceOf(target);
raceCoinBalance[target] = 0;
}
lastRaceCoinSaveTime[target] = block.timestamp;
} else {
battleCooldown[player] = block.timestamp + 10 minutes;
emit PlayerAttacked(player, target, false, 0);
}
}
function getPlayersBattleStats(address player) external view returns (uint256, uint256, uint256, uint256){
return (attackPower[player], defendPower[player], plunderPower[player], battleCooldown[player]);
}
function getPlayersBaseAttributesInt(address player) external view returns (uint256, uint256, uint256, uint256){
return (productionBaseValue[player], attackBaseValue[player], defendBaseValue[player], plunderBaseValue[player]);
}
function getPlayersAttributesInt(address player) external view returns (uint256, uint256, uint256, uint256){
return (getRaceCoinProduction(player), attackPower[player], defendPower[player], plunderPower[player]);
}
function getPlayersAttributesMult(address player) external view returns (uint256, uint256, uint256, uint256){
return (productionMultiplier[player], attackMultiplier[player], defendMultiplier[player], plunderMultiplier[player]);
}
function withdrawEther(uint256 amount) external {
require(amount <= ethBalance[msg.sender]);
ethBalance[msg.sender] -= amount;
msg.sender.transfer(amount);
}
function getBalance() external view returns(uint256) {
return totalEtherPool;
}
function addTotalEtherPool(uint256 amount) external{
require(actionContracts[msg.sender]);
require(amount > 0);
totalEtherPool += amount;
}
function correctPool(uint256 _count) external onlyAdmin {
require( _count > 0);
totalEtherPool += _count;
}
// To display
function getGameInfo(address player) external view returns (uint256, uint256, uint256, uint256, uint256, uint256, uint256){
return ( totalEtherPool, totalRaceCoinProduction,nextSnapshotTime, balanceOf(player), ethBalance[player],
getRaceCoinProduction(player),raceCoinBalance[player]);
}
function getMatchFunInfo(address player) external view returns (uint256, uint256){
return (raceCoinSnapshots[player][totalRaceCoinSnapshots.length - 1],
totalRaceCoinSnapshots[totalRaceCoinSnapshots.length - 1]);
}
function getGameCurrTime(address player) external view returns (uint256){
return block.timestamp;
}
function claimOffLineDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external {
require(startSnapshot <= endSnapShot);
require(startSnapshot >= lastProductionFundClaim[msg.sender]);
require(endSnapShot < allocatedProductionSnapshots.length);
uint256 offLineShare;
uint256 previousProduction = raceCoinProductionSnapshots[msg.sender][lastProductionFundClaim[msg.sender] - 1];
for (uint256 i = startSnapshot; i <= endSnapShot; i++) {
uint256 productionDuringSnapshot = raceCoinProductionSnapshots[msg.sender][i];
bool soldAllProduction = raceCoinProductionZeroedSnapshots[msg.sender][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
offLineShare += (allocatedProductionSnapshots[i] * productionDuringSnapshot) / totalRaceCoinProductionSnapshots[i];
}
if (raceCoinProductionSnapshots[msg.sender][endSnapShot] == 0 && !raceCoinProductionZeroedSnapshots[msg.sender][endSnapShot] && previousProduction > 0) {
raceCoinProductionSnapshots[msg.sender][endSnapShot] = previousProduction; // Checkpoint for next claim
}
lastProductionFundClaim[msg.sender] = endSnapShot + 1;
uint256 referalDivs;
if (referer != address(0) && referer != msg.sender) {
referalDivs = offLineShare.mul(refererPercent).div(100); // 5%
ethBalance[referer] += referalDivs;
refererDivsBalance[referer] += referalDivs;
emit ReferalGain(referer, msg.sender, referalDivs);
}
ethBalance[msg.sender] += offLineShare - referalDivs;
}
// To display on website
function viewOffLineDividends(address player) external view returns (uint256, uint256, uint256) {
uint256 startSnapshot = lastProductionFundClaim[player];
uint256 latestSnapshot = allocatedProductionSnapshots.length - 1;
uint256 offLineShare;
uint256 previousProduction = raceCoinProductionSnapshots[player][lastProductionFundClaim[player] - 1];
for (uint256 i = startSnapshot; i <= latestSnapshot; i++) {
uint256 productionDuringSnapshot = raceCoinProductionSnapshots[player][i];
bool soldAllProduction = raceCoinProductionZeroedSnapshots[player][i];
if (productionDuringSnapshot == 0 && !soldAllProduction) {
productionDuringSnapshot = previousProduction;
} else {
previousProduction = productionDuringSnapshot;
}
offLineShare += (allocatedProductionSnapshots[i] * productionDuringSnapshot) / totalRaceCoinProductionSnapshots[i];
}
return (offLineShare, startSnapshot, latestSnapshot);
}
function claimRaceCoinDividends(address referer, uint256 startSnapshot, uint256 endSnapShot) external {
require(startSnapshot <= endSnapShot);
require(startSnapshot >= lastRaceCoinFundClaim[msg.sender]);
require(endSnapShot < allocatedRaceCoinSnapshots.length);
uint256 dividendsShare;
for (uint256 i = startSnapshot; i <= endSnapShot; i++) {
dividendsShare += (allocatedRaceCoinSnapshots[i] * raceCoinSnapshots[msg.sender][i]) / (totalRaceCoinSnapshots[i] + 1);
}
lastRaceCoinFundClaim[msg.sender] = endSnapShot + 1;
uint256 referalDivs;
if (referer != address(0) && referer != msg.sender) {
referalDivs = dividendsShare.mul(refererPercent).div(100); // 5%
ethBalance[referer] += referalDivs;
refererDivsBalance[referer] += referalDivs;
emit ReferalGain(referer, msg.sender, referalDivs);
}
ethBalance[msg.sender] += dividendsShare - referalDivs;
}
// To display
function viewUnclaimedRaceCoinDividends(address player) external view returns (uint256, uint256, uint256) {
uint256 startSnapshot = lastRaceCoinFundClaim[player];
uint256 latestSnapshot = allocatedRaceCoinSnapshots.length - 1; // No snapshots to begin with
uint256 dividendsShare;
for (uint256 i = startSnapshot; i <= latestSnapshot; i++) {
dividendsShare += (allocatedRaceCoinSnapshots[i] * raceCoinSnapshots[player][i]) / (totalRaceCoinSnapshots[i] + 1);
}
return (dividendsShare, startSnapshot, latestSnapshot);
}
function getRefererDivsBalance(address player) external view returns (uint256){
return refererDivsBalance[player];
}
function updatePlayersRaceCoinFromPurchase(address player, uint256 purchaseCost) internal {
uint256 unclaimedRaceCoin = balanceOfUnclaimedRaceCoin(player);
if (purchaseCost > unclaimedRaceCoin) {
uint256 raceCoinDecrease = purchaseCost - unclaimedRaceCoin;
require(raceCoinBalance[player] >= raceCoinDecrease);
roughSupply -= raceCoinDecrease;
raceCoinBalance[player] -= raceCoinDecrease;
} else {
uint256 raceCoinGain = unclaimedRaceCoin - purchaseCost;
roughSupply += raceCoinGain;
raceCoinBalance[player] += raceCoinGain;
}
lastRaceCoinSaveTime[player] = block.timestamp;
}
function fundRaceCoinDeposit(uint256 amount) external {
updatePlayersRaceCoinFromPurchase(msg.sender, amount);
raceCoinSnapshots[msg.sender][totalRaceCoinSnapshots.length - 1] += amount;
totalRaceCoinSnapshots[totalRaceCoinSnapshots.length - 1] += amount;
}
// Allocate divs for the day (00:00 cron job)
function snapshotDailyRaceCoinFunding() external onlyAdmin whenNotPaused {
uint256 todaysRaceCoinFund = (totalEtherPool * bonusMatchFunPercent) / 100; // 10% of pool daily
uint256 todaysOffLineFund = (totalEtherPool * bonusOffLinePercent) / 100; // 10% of pool daily
if(totalRaceCoinSnapshots[totalRaceCoinSnapshots.length - 1] > 0){
totalEtherPool -= todaysRaceCoinFund;
}
totalEtherPool -= todaysOffLineFund;
totalRaceCoinSnapshots.push(0);
allocatedRaceCoinSnapshots.push(todaysRaceCoinFund);
totalRaceCoinProductionSnapshots.push(totalRaceCoinProduction);
allocatedProductionSnapshots.push(todaysOffLineFund);
nextSnapshotTime = block.timestamp + 24 hours;
}
}
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;
}
} | Player production base value
| mapping(address => uint256) private productionBaseValue; | 1,015,302 | [
1,
12148,
12449,
1026,
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,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
12449,
2171,
620,
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
] |
./full_match/80001/0x8cAf74f3265827F016467B8e10E365A6a4F322C1/sources/contracts/dep/credentials.sol | Mapping of outer wallet to Account struct | mapping(address => CredentialPublicKey[]) public credentials;
| 9,439,301 | [
1,
3233,
434,
6390,
9230,
358,
6590,
1958,
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,
2874,
12,
2867,
516,
15232,
9632,
63,
5717,
1071,
4448,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.8.7;
// SPDX-Licence-Identifier: GPL-3.0-or-later
/*
kkkkkkkOK0kkOXN0kkOXKkkkkkk0WMMM0kXMMMW0kkkkOXMMMNOdoodkXMWWKxoood0WMMMNOkkkk0NMMMW0doookXMWKkkkKMMN0kkkkONXkkkkkkkOK0kkOXMW0xoooxKWMXkkkOXMKkkONXkxkk
........l:...x0;..,Oo......:XMWX:,0MWMK;.....xMM0:. .,ONx'. .lXNd,......;kWXl. .,kNl...oWM0,....'ko........c:...kXl. .'xNd....dWo..'OKdl;.
;. .':o, .x0' .kl .,,oN0c'.'kNMMk. cWNc ', :x' .:. .xd. .,'. '0d ';. ,0l lWMd. lx;. ':o, .xd. .:. 'Oo ;Xo .kW0ocd
Wx. '0WK, .x0' .kl cNWWK; .,kMWo . ,KX; dO;..cl. ;Kd..'dc lKk; .xc oK, .kl lWWc .. :XMx. ,0WK, .xl lX; .xo .xo .kk..lx
Mk. '0MK; ok. .kl :KKXO' .dllNX; ', .kX; c00KXNx. .x0KXNXc oXO; .dc oNOxxkKc lWK, ,, '0Mk. ,KMK, .xl lX: .dl cc .kO:;;;
Mk. '0MK, .. .kl ..l0: ,;.oO' :l dWo ..,lK0, .':kXc oXO; .d: oMMMMMWc lWO. cc .xMk. ,KMK, .xl lX: .dl . ., .kKo;,,
Mk. '0MK, .. .kl .''lX0, .;:xd. ox. cNNxc,'. :X0o;,. .xc oXO; .d: oMMMMMNc lWd dd lWk. ,KMK, .xl lX: .dl .;. .kMWdc:
Mk. '0MK, .oO' .kl cXNWWMXo. lNWl .' ,0NXXXXd. 'ONXXXK; c: lXO; .dc oNkooxKc lNc .. ;Xk. ,KMK, .xl lX: .dl .o, .kMWOxo
Mk. '0MK, .x0' .kl cXNWMMMWKl;kX; .xo..'kk. ,o;..lKc lc oKk; .xc o0, .kl l0, .Ok. ,KMK, .xl lK; .xo .kl .OWNNXc
Mk. '0MK; .x0' .kl ..'lNMMMMWdxO. .dk, ol .' :k' .,. .xo ':,. 'Od .,. ,0l lk. 'xx' dk. ,KMK, .xx. .,. 'Oo .kO. .kKdol.
MO,..:KMXc..'kK:..;Od......cXMMMMM0kx,..cXWo...o0o'.....:0Wk;.....'dNKc. 'xNXo'.....;ONo...od'..lNNl...dO,..cXMXc..,kNd'.....,kWd..,ONl...;0WWWNl
MNK00KWMWX00KNWK00KWN000000XWMMMMMWWNKK0XWMN000XWWXOxkkKWMMMN0kxkOXWMMN0dllooxKWWMMXOkkk0NMWX000XX000XMMX000XNK00XWMWX00KNMMXOkkk0NMMNK0KNWX000KNMMMWX
*/
/// @author: galaxis.xyz - The platform for decentralized communities.
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777.sol";
import "./ssp/community_interface.sol";
import "./ssp/sale_configuration.sol";
import "./ssp/recovery.sol";
import "./ssp/IRNG.sol";
import "./ssp/dusty.sol";
import "./ssp/card_with_card.sol";
import "./ssp/token_interface.sol";
struct sale_data {
uint256 maxTokens;
uint256 mintPosition;
address[] wallets;
uint16[] shares;
uint256 fullPrice;
uint256 discountPrice;
uint256 presaleStart;
uint256 presaleEnd;
uint256 saleStart;
uint256 saleEnd;
uint256 dustPrice;
bool areTokensLocked;
uint256 maxFreeEC;
uint256 totalFreeEC;
uint256 maxDiscount;
uint256 totalDiscount;
uint256 freePerAddress;
uint256 discountedPerAddress;
string tokenPreRevealURI;
address signer;
bool presaleIsActive;
bool saleIsActive;
bool dustMintingActive;
uint256 freeClaimedByThisUser;
uint256 discountedClaimedByThisUser;
address etherCards;
address DUST;
address ecVault;
uint256 maxPerSaleMint;
uint256 MaxUserMintable;
uint256 userMinted;
bool randomReceived;
bool secondReceived;
uint256 randomCL;
uint256 randomCL2;
uint256 ts1;
uint256 ts;
}
struct sale_params {
uint256 projectID;
token_interface token;
IERC721 ec;
address dust;
uint256 maxTokens;
uint256 maxDiscount; //<--- max sold in presale across presale dust / eth
uint256 maxPerSaleMint;
uint256 clientMintLimit;
uint256 ecMintLimit;
uint256 discountedPerAddress; //<-- should apply to all presale
uint256 freeForEC; //<-- for EC card holders
uint256 discountPrice; //<-- for EC card holders - if zero not available should have *** dust ***
uint256 discountDustPrice; //<-- for EC card holders - if zero not available should have *** dust ***
uint256 fullPrice;
address signer;
uint256 saleStart;
uint256 saleEnd;
uint256 presaleStart;
uint256 presaleEnd;
uint256 fullDustPrice;
address[] wallets;
uint16[] shares;
}
// check approval limit - start / end of presale
contract The_Association_Sales is
sale_configuration,
Ownable,
recovery,
ReentrancyGuard,
dusty,
card_with_card
{
using SafeMath for uint256;
using Strings for uint256;
uint256 public immutable projectID;
token_interface public _token;
uint256 immutable _MaxUserMintable;
uint256 _userMinted;
uint256 _ts1;
uint256 _ts2;
address private immutable _DUST;
IERC721 private immutable _EC;
uint16 public batchNumber;
mapping(address => uint256) _freeClaimedPerWallet;
mapping(address => uint256) _discountedClaimedPerWallet;
event RandomProcessed(
uint256 stage,
uint256 randUsed_,
uint256 _start,
uint256 _stop,
uint256 _supply
);
event batchWhitelistMint(uint16 indexed batchNumber, address receiver);
event ETHPresale(address from, uint256 number_of_items, uint256 price);
event ETHSale(address buyer, uint256 number_to_buy, uint256 ethAmount);
event Allowed(address, bool);
modifier onlyAllowed() {
require(
_token.permitted(msg.sender) || (msg.sender == owner()),
"Unauthorised"
);
_;
}
// the constructor takes the bare minimum to conduct a presale and sale.
constructor(sale_params memory sp)
dusty(
sp.dust,
sp.signer,
sp.fullDustPrice,
sp.discountDustPrice,
sp.maxPerSaleMint,
sp.wallets,
sp.shares
)
card_with_card(sp.signer)
{
projectID = sp.projectID;
_EC = sp.ec;
_token = sp.token;
_DUST = sp.dust;
_MaxUserMintable = sp.maxTokens - (sp.clientMintLimit + sp.ecMintLimit);
_maxSupply = sp.maxTokens;
_maxDiscount = sp.maxDiscount;
_discountedPerAddress = sp.discountedPerAddress;
_discountPrice = sp.discountPrice;
_fullPrice = sp.fullPrice;
_saleStart = sp.saleStart;
_saleEnd = sp.saleEnd;
_presaleStart = sp.presaleStart;
_presaleEnd = sp.presaleEnd;
_maxFreeEC = sp.freeForEC;
}
function _split(uint256 amount) internal {
// console.log("num wallets",wallets.length);
bool sent;
uint256 _total;
for (uint256 j = 0; j < wallets.length; j++) {
uint256 _amount = (amount * shares[j]) / 1000;
if (j == wallets.length - 1) {
_amount = amount - _total;
} else {
_total += _amount;
}
(sent, ) = wallets[j].call{value: _amount}(""); // don't use send or xfer (gas)
require(sent, "Failed to send Ether");
}
}
function setup(uint16 _batchNumber) external onlyAllowed {
batchNumber = _batchNumber;
}
function checkDiscountAvailable(address buyer)
public
view
returns (
bool[3] memory,
bool,
uint256,
uint256,
uint256
)
{
bool _final = false;
return (
[false, false, true],
_final, // _final,
_discountedClaimedPerWallet[buyer], // EC
presold[buyer], // Not in use.
_token.availableToMint()
);
}
function mint_approved(
vData memory info,
uint256 number_of_items_requested,
uint16 _batchNumber
) external {
require(batchNumber == _batchNumber, "!batch");
address from = msg.sender;
require(verify(info), "Unauthorised access secret");
_discountedClaimedPerWallet[msg.sender] += 1;
require(
_discountedClaimedPerWallet[msg.sender] <= 1,
"Number exceeds max discounted per address"
);
presold[from] = 1;
_mintCards(number_of_items_requested, from);
emit batchWhitelistMint(_batchNumber, msg.sender);
}
// make sure this respects ec_limit and client_limit
function mint(uint256 numberOfCards) external {
_discountedClaimedPerWallet[msg.sender] += numberOfCards;
require(
_discountedClaimedPerWallet[msg.sender] <= maxPerSaleMint,
"Number exceeds max discounted per address"
);
require(checkSaleIsActive(), "sale is not open");
require(
numberOfCards <= maxPerSaleMint,
"Exceeds max per Transaction Mint"
);
_mintPayable(numberOfCards, msg.sender, _fullPrice);
}
function _mintPayable(
uint256 numberOfCards,
address recipient,
uint256 price
) internal override {
_mintCards(numberOfCards, recipient);
}
function _mintCards(uint256 numberOfCards, address recipient)
internal
override(dusty, card_with_card)
{
_userMinted += numberOfCards;
require(
_userMinted <= _MaxUserMintable,
"This exceeds maximum number of user mintable cards"
);
_token.mintCards(numberOfCards, recipient);
}
function _mintDiscountCards(uint256 numberOfCards, address recipient)
internal
override(dusty, card_with_card)
{
_totalDiscount += numberOfCards;
require(
_maxDiscount >= _totalDiscount,
"Too many discount tokens claimed"
);
_mintCards(numberOfCards, recipient);
}
function _mintDiscountPayable(
uint256 numberOfCards,
address recipient,
uint256 price
) internal override(card_with_card) {
require(msg.value == numberOfCards.mul(price), "wrong amount sent");
_mintDiscountCards(numberOfCards, recipient);
// _split(msg.value);
}
function setSaleDates(uint256 _start, uint256 _end) external onlyAllowed {
_saleStart = _start;
_saleEnd = _end;
}
function setPresaleDates(uint256 _start, uint256 _end)
external
onlyAllowed
{
_presaleStart = _start;
_presaleEnd = _end;
}
function setMaxPerSaleMint(uint256 _maxPerSaleMint) external onlyOwner {
maxPerSaleMint = _maxPerSaleMint;
}
function checkSaleIsActive() public view override returns (bool) {
if ((_saleStart <= block.timestamp) && (_saleEnd >= block.timestamp))
return true;
return false;
}
function checkPresaleIsActive() public view override returns (bool) {
if (
(_presaleStart <= block.timestamp) &&
(_presaleEnd >= block.timestamp)
) return true;
return false;
}
function setWallets(
address payable[] memory _wallets,
uint16[] memory _shares
) public onlyOwner {
require(_wallets.length == _shares.length, "!l");
wallets = _wallets;
shares = _shares;
}
receive() external payable {
_split(msg.value);
}
function tellEverything(address addr)
external
view
returns (sale_data memory)
{
// if community module active - get the community.taken[msg.sender]
token_interface.TKS memory tokenData = _token.tellEverything();
return
sale_data(
_maxSupply,
tokenData._mintPosition,
wallets,
shares,
_fullPrice,
_discountPrice,
_presaleStart,
_presaleEnd,
_saleStart,
_saleEnd,
_dustPrice,
tokenData._lockTillSaleEnd,
_maxFreeEC,
_totalFreeEC,
_maxDiscount,
_totalDiscount,
_freePerAddress,
_discountedPerAddress,
_token.tokenPreRevealURI(),
_signer,
checkPresaleIsActive(),
checkSaleIsActive(),
checkSaleIsActive() &&
(fullDustPrice > 0 || discountDustPrice > 0),
_freeClaimedPerWallet[addr],
_discountedClaimedPerWallet[addr],
address(_EC),
_DUST,
_ecVault,
maxPerSaleMint,
_MaxUserMintable,
_userMinted,
tokenData._randomReceived,
tokenData._secondReceived,
tokenData._randomCL,
tokenData._randomCL2,
tokenData._ts1,
tokenData._ts2
);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Registry.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(
address account,
bytes32 _interfaceHash,
address implementer
) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(
address recipient,
uint256 amount,
bytes calldata data
) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Revoke an account's operator status for the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
pragma solidity ^0.8.7;
interface community_interface {
function community_claimed(address) external view returns (uint256);
function communityPurchase(
address recipient,
uint256 tokenCount,
bytes memory signature,
uint256 role
) external payable;
}
pragma solidity ^0.8.7;
contract sale_configuration {
uint256 _maxSupply;
uint256 _clientMintLimit;
uint256 _ecMintLimit;
uint256 _fullPrice;
uint256 _discountPrice; // obsolete
uint256 _communityPrice; // obsolete
uint256 _presaleStart; // obsolete
uint256 _presaleEnd; // obsolete
uint256 _saleStart;
uint256 _saleEnd;
uint256 _dustPrice; // obsolete
uint256 _discountedPerAddress; // obsolete
uint256 _totalDiscount; // obsolete
uint256 _maxDiscount; // obsolete
uint256 _maxPerSaleMint;
uint256 _freePerAddress;
address _signer;
uint256 _maxFreeEC; // obsolete
uint256 _totalFreeEC; // obsolete
uint256 _ecMintPosition;
uint256 _clientMintPosition;
address _ecVault;
}
pragma solidity ^0.8.7;
// SPDX-Licence-Identifier: RIGHT-CLICK-SAVE-ONLY
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract recovery is Ownable {
// blackhole prevention methods
function retrieveETH() external onlyOwner {
(bool sent, ) =
payable(msg.sender).call{value: address(this).balance}(""); // don't use send or xfer (gas)
require(sent, "Failed to send Ether");
}
function retrieveERC20(address _tracker, uint256 amount)
external
onlyOwner
{
IERC20(_tracker).transfer(msg.sender, amount);
}
function retrieve721(address _tracker, uint256 id) external onlyOwner {
IERC721(_tracker).transferFrom(address(this), msg.sender, id);
}
}
pragma solidity ^0.8.7;
interface IRNG {
function requestRandomNumber() external returns (bytes32);
function requestRandomNumberWithCallback() external returns (bytes32);
function isRequestComplete(bytes32 requestId)
external
view
returns (bool isCompleted);
function randomNumber(bytes32 requestId)
external
view
returns (uint256 randomNum);
function setAuth(address user, bool grant) external;
}
pragma solidity ^0.8.7;
// SPDX-Licence-Identifier: RIGHT-CLICK-SAVE-ONLY
import "@openzeppelin/contracts/utils/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777.sol";
//import "hardhat/console.sol";
abstract contract dusty is IERC777Recipient, ReentrancyGuard {
// struct community_data {
// uint256 start;
// uint256 end;
// uint256 price;
// bool isDust;
// uint256 max_purchase;
// address purchaser;
// }
address DUST_TOKEN;
address signer;
address[] wallets;
uint16[] shares;
uint256 fullDustPrice;
uint256 discountDustPrice;
uint256 maxPerSaleMint;
mapping(address => uint256) presold;
bytes32 private constant TOKENS_RECIPIENT_INTERFACE_HASH =
keccak256("ERC777TokensRecipient");
IERC1820Registry internal constant _ERC1820_REGISTRY =
IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
event DustPresale(address from, uint256 number_of_items, uint256 price);
event DustSale(address buyer, uint256 number_to_buy, uint256 dustAmount);
constructor(
address dust,
address _signer,
uint256 _fullDustPrice,
uint256 _discountDustPrice,
uint256 _maxPerSaleMint,
address[] memory _wallets,
uint16[] memory _shares
) {
DUST_TOKEN = dust;
_ERC1820_REGISTRY.setInterfaceImplementer(
address(this),
TOKENS_RECIPIENT_INTERFACE_HASH,
address(this)
);
wallets = _wallets;
shares = _shares;
signer = _signer;
fullDustPrice = _fullDustPrice;
discountDustPrice = _discountDustPrice;
maxPerSaleMint = _maxPerSaleMint;
}
// https://twitter.com/nicksdjohnson/status/1485769228481605639?s=20&t=22PZlf-8awaea2bubNw72A
// ```
// bytes4 selector = bytes4(data[:4]);
// uint256 id = uint256(bytes32(data[4:36]));
// ```
struct vData {
bool mint_free;
uint256 max_mint;
address from;
uint256 start;
uint256 end;
uint256 eth_price;
uint256 dust_price;
bytes signature;
}
function checkSaleIsActive() public view virtual returns (bool);
function checkPresaleIsActive() public view virtual returns (bool);
function tokensReceived(
address,
address from,
address,
uint256 amount,
bytes calldata userData,
bytes calldata
) external override nonReentrant {}
function _mintCards(uint256 numberOfCards, address recipient)
internal
virtual;
function _mintDiscountCards(uint256 numberOfCards, address recipient)
internal
virtual;
function verify(vData memory info) public view returns (bool) {
require(info.from != address(0), "INVALID_SIGNER");
bytes memory cat =
abi.encode(
info.from,
info.start,
info.end,
info.eth_price,
info.dust_price,
info.max_mint,
info.mint_free
);
// console.log("data-->");
// console.logBytes(cat);
bytes32 hash = keccak256(cat);
// console.log("hash ->");
// console.logBytes32(hash);
require(info.signature.length == 65, "Invalid signature length");
bytes32 sigR;
bytes32 sigS;
uint8 sigV;
bytes memory signature = info.signature;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
sigR := mload(add(signature, 0x20))
sigS := mload(add(signature, 0x40))
sigV := byte(0, mload(add(signature, 0x60)))
}
bytes32 data =
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
address recovered = ecrecover(data, sigV, sigR, sigS);
return signer == recovered;
}
}
pragma solidity ^0.8.7;
// SPDX-Licence-Identifier: RIGHT-CLICK-SAVE-ONLY
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
// import "hardhat/console.sol";
abstract contract card_with_card {
struct saleInfo {
address token_address;
uint256 start;
uint256 end;
uint256 price;
uint256 max_per_user;
uint256 total;
bool oneForOne;
bytes signature;
}
address cwc_signer;
constructor(address _signer) {
cwc_signer = _signer;
}
function _mintCards(uint256 numberOfCards, address recipient)
internal
virtual;
function _mintDiscountCards(uint256 numberOfCards, address recipient)
internal
virtual;
function _mintDiscountPayable(
uint256 numberOfCards,
address recipient,
uint256 price
) internal virtual;
function _mintPayable(
uint256 numberOfCards,
address recipient,
uint256 price
) internal virtual;
function verify(saleInfo calldata sp) internal view returns (bool) {
require(sp.token_address != address(0), "INVALID_TOKEN_ADDRESS");
bytes memory cat =
abi.encode(
sp.token_address,
sp.start,
sp.end,
sp.price,
sp.max_per_user,
sp.total,
sp.oneForOne
);
bytes32 hash = keccak256(cat);
require(sp.signature.length == 65, "Invalid signature length");
bytes32 sigR;
bytes32 sigS;
uint8 sigV;
bytes memory signature = sp.signature;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
sigR := mload(add(signature, 0x20))
sigS := mload(add(signature, 0x40))
sigV := byte(0, mload(add(signature, 0x60)))
}
bytes32 data =
keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
address recovered = ecrecover(data, sigV, sigR, sigS);
return cwc_signer == recovered;
}
}
pragma solidity ^0.8.7;
interface token_interface {
struct TKS {
// Token Kitchen Sink
uint256 _mintPosition;
uint256 _ts1;
uint256 _ts2;
bool _randomReceived;
bool _secondReceived;
uint256 _randomCL;
uint256 _randomCL2;
bool _lockTillSaleEnd;
}
function setAllowed(address _addr, bool _state) external;
function permitted(address) external view returns (bool);
function mintCards(uint256 numberOfCards, address recipient) external;
function tellEverything() external view returns (TKS memory);
function tokenPreRevealURI() external view returns (string memory);
function availableToMint() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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
// 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);
} | if community module active - get the community.taken[msg.sender] | function tellEverything(address addr)
external
view
returns (sale_data memory)
{
token_interface.TKS memory tokenData = _token.tellEverything();
return
sale_data(
_maxSupply,
tokenData._mintPosition,
wallets,
shares,
_fullPrice,
_discountPrice,
_presaleStart,
_presaleEnd,
_saleStart,
_saleEnd,
_dustPrice,
tokenData._lockTillSaleEnd,
_maxFreeEC,
_totalFreeEC,
_maxDiscount,
_totalDiscount,
_freePerAddress,
_discountedPerAddress,
_token.tokenPreRevealURI(),
_signer,
checkPresaleIsActive(),
checkSaleIsActive(),
checkSaleIsActive() &&
(fullDustPrice > 0 || discountDustPrice > 0),
_freeClaimedPerWallet[addr],
_discountedClaimedPerWallet[addr],
address(_EC),
_DUST,
_ecVault,
maxPerSaleMint,
_MaxUserMintable,
_userMinted,
tokenData._randomReceived,
tokenData._secondReceived,
tokenData._randomCL,
tokenData._randomCL2,
tokenData._ts1,
tokenData._ts2
);
}
| 9,831,712 | [
1,
430,
19833,
1605,
2695,
300,
336,
326,
19833,
18,
29113,
63,
3576,
18,
15330,
65,
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,
9276,
21465,
4274,
12,
2867,
3091,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
87,
5349,
67,
892,
3778,
13,
203,
565,
288,
203,
203,
3639,
1147,
67,
5831,
18,
56,
47,
55,
3778,
1147,
751,
273,
389,
2316,
18,
88,
1165,
21465,
4274,
5621,
203,
3639,
327,
203,
5411,
272,
5349,
67,
892,
12,
203,
7734,
389,
1896,
3088,
1283,
16,
203,
7734,
1147,
751,
6315,
81,
474,
2555,
16,
203,
7734,
17662,
2413,
16,
203,
7734,
24123,
16,
203,
7734,
389,
2854,
5147,
16,
203,
7734,
389,
23650,
5147,
16,
203,
7734,
389,
12202,
5349,
1685,
16,
203,
7734,
389,
12202,
5349,
1638,
16,
203,
7734,
389,
87,
5349,
1685,
16,
203,
7734,
389,
87,
5349,
1638,
16,
203,
7734,
389,
72,
641,
5147,
16,
203,
7734,
1147,
751,
6315,
739,
56,
737,
30746,
1638,
16,
203,
7734,
389,
1896,
9194,
7228,
16,
203,
7734,
389,
4963,
9194,
7228,
16,
203,
7734,
389,
1896,
9866,
16,
203,
7734,
389,
4963,
9866,
16,
203,
7734,
389,
9156,
2173,
1887,
16,
203,
7734,
389,
23650,
329,
2173,
1887,
16,
203,
7734,
389,
2316,
18,
2316,
1386,
426,
24293,
3098,
9334,
203,
7734,
389,
2977,
264,
16,
203,
7734,
866,
12236,
5349,
2520,
3896,
9334,
203,
7734,
866,
30746,
2520,
3896,
9334,
203,
7734,
866,
30746,
2520,
3896,
1435,
597,
203,
10792,
261,
2854,
40,
641,
5147,
405,
374,
747,
12137,
40,
641,
5147,
405,
374,
3631,
203,
7734,
389,
9156,
9762,
329,
2173,
16936,
63,
4793,
6487,
203,
7734,
2
] |
// File: contracts/lib/IOracle.sol
pragma solidity 0.6.5;
interface IOracle {
function getData() external returns (uint256, bool);
}
// File: contracts/lib/FullMath.sol
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity 0.6.5;
// taken from https://medium.com/coinmonks/math-in-solidity-part-3-percents-and-proportions-4db014e080b1
// license is CC-BY-4.0
library FullMath {
function fullMul(uint256 x, uint256 y) internal pure returns (uint256 l, uint256 h) {
uint256 mm = mulmod(x, y, uint256(-1));
l = x * y;
h = mm - l;
if (mm < l) h -= 1;
}
function fullDiv(
uint256 l,
uint256 h,
uint256 d
) private pure returns (uint256) {
uint256 pow2 = d & -d;
d /= pow2;
l /= pow2;
l += h * ((-pow2) / pow2 + 1);
uint256 r = 1;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
r *= 2 - d * r;
return l * r;
}
function mulDiv(
uint256 x,
uint256 y,
uint256 d
) internal pure returns (uint256) {
(uint256 l, uint256 h) = fullMul(x, y);
uint256 mm = mulmod(x, y, d);
if (mm > l) h -= 1;
l -= mm;
if (h == 0) return l / d;
require(h < d, 'FullMath: FULLDIV_OVERFLOW');
return fullDiv(l, h, d);
}
}
// File: contracts/lib/Babylonian.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.5;
// computes square roots using the babylonian method
// https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method
library Babylonian {
// credit for this implementation goes to
// https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol#L687
function sqrt(uint256 x) internal pure returns (uint256) {
if (x == 0) return 0;
// this block is equivalent to r = uint256(1) << (BitMath.mostSignificantBit(x) / 2);
// however that code costs significantly more gas
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) {
xx >>= 128;
r <<= 64;
}
if (xx >= 0x10000000000000000) {
xx >>= 64;
r <<= 32;
}
if (xx >= 0x100000000) {
xx >>= 32;
r <<= 16;
}
if (xx >= 0x10000) {
xx >>= 16;
r <<= 8;
}
if (xx >= 0x100) {
xx >>= 8;
r <<= 4;
}
if (xx >= 0x10) {
xx >>= 4;
r <<= 2;
}
if (xx >= 0x8) {
r <<= 1;
}
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return (r < r1 ? r : r1);
}
}
// File: contracts/lib/BitMath.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.5;
library BitMath {
// returns the 0 indexed position of the most significant bit of the input x
// s.t. x >= 2**msb and x < 2**(msb+1)
function mostSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::mostSignificantBit: zero');
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
r += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
r += 64;
}
if (x >= 0x100000000) {
x >>= 32;
r += 32;
}
if (x >= 0x10000) {
x >>= 16;
r += 16;
}
if (x >= 0x100) {
x >>= 8;
r += 8;
}
if (x >= 0x10) {
x >>= 4;
r += 4;
}
if (x >= 0x4) {
x >>= 2;
r += 2;
}
if (x >= 0x2) r += 1;
}
// returns the 0 indexed position of the least significant bit of the input x
// s.t. (x & 2**lsb) != 0 and (x & (2**(lsb) - 1)) == 0)
// i.e. the bit at the index is set and the mask of all lower bits is 0
function leastSignificantBit(uint256 x) internal pure returns (uint8 r) {
require(x > 0, 'BitMath::leastSignificantBit: zero');
r = 255;
if (x & uint128(-1) > 0) {
r -= 128;
} else {
x >>= 128;
}
if (x & uint64(-1) > 0) {
r -= 64;
} else {
x >>= 64;
}
if (x & uint32(-1) > 0) {
r -= 32;
} else {
x >>= 32;
}
if (x & uint16(-1) > 0) {
r -= 16;
} else {
x >>= 16;
}
if (x & uint8(-1) > 0) {
r -= 8;
} else {
x >>= 8;
}
if (x & 0xf > 0) {
r -= 4;
} else {
x >>= 4;
}
if (x & 0x3 > 0) {
r -= 2;
} else {
x >>= 2;
}
if (x & 0x1 > 0) r -= 1;
}
}
// File: contracts/lib/FixedPoint.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.5;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
library FixedPoint {
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
struct uq112x112 {
uint224 _x;
}
// range: [0, 2**144 - 1]
// resolution: 1 / 2**112
struct uq144x112 {
uint256 _x;
}
uint8 public constant RESOLUTION = 112;
uint256 public constant Q112 = 0x10000000000000000000000000000; // 2**112
uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; // 2**224
uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits)
// encode a uint112 as a UQ112x112
function encode(uint112 x) internal pure returns (uq112x112 memory) {
return uq112x112(uint224(x) << RESOLUTION);
}
// encodes a uint144 as a UQ144x112
function encode144(uint144 x) internal pure returns (uq144x112 memory) {
return uq144x112(uint256(x) << RESOLUTION);
}
// decode a UQ112x112 into a uint112 by truncating after the radix point
function decode(uq112x112 memory self) internal pure returns (uint112) {
return uint112(self._x >> RESOLUTION);
}
// decode a UQ144x112 into a uint144 by truncating after the radix point
function decode144(uq144x112 memory self) internal pure returns (uint144) {
return uint144(self._x >> RESOLUTION);
}
// multiply a UQ112x112 by a uint, returning a UQ144x112
// reverts on overflow
function mul(uq112x112 memory self, uint256 y) internal pure returns (uq144x112 memory) {
uint256 z = 0;
require(y == 0 || (z = self._x * y) / y == self._x, 'FixedPoint::mul: overflow');
return uq144x112(z);
}
// multiply a UQ112x112 by an int and decode, returning an int
// reverts on overflow
function muli(uq112x112 memory self, int256 y) internal pure returns (int256) {
uint256 z = FullMath.mulDiv(self._x, uint256(y < 0 ? -y : y), Q112);
require(z < 2**255, 'FixedPoint::muli: overflow');
return y < 0 ? -int256(z) : int256(z);
}
// multiply a UQ112x112 by a UQ112x112, returning a UQ112x112
// lossy
function muluq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
if (self._x == 0 || other._x == 0) {
return uq112x112(0);
}
uint112 upper_self = uint112(self._x >> RESOLUTION); // * 2^0
uint112 lower_self = uint112(self._x & LOWER_MASK); // * 2^-112
uint112 upper_other = uint112(other._x >> RESOLUTION); // * 2^0
uint112 lower_other = uint112(other._x & LOWER_MASK); // * 2^-112
// partial products
uint224 upper = uint224(upper_self) * upper_other; // * 2^0
uint224 lower = uint224(lower_self) * lower_other; // * 2^-224
uint224 uppers_lowero = uint224(upper_self) * lower_other; // * 2^-112
uint224 uppero_lowers = uint224(upper_other) * lower_self; // * 2^-112
// so the bit shift does not overflow
require(upper <= uint112(-1), 'FixedPoint::muluq: upper overflow');
// this cannot exceed 256 bits, all values are 224 bits
uint256 sum = uint256(upper << RESOLUTION) + uppers_lowero + uppero_lowers + (lower >> RESOLUTION);
// so the cast does not overflow
require(sum <= uint224(-1), 'FixedPoint::muluq: sum overflow');
return uq112x112(uint224(sum));
}
// divide a UQ112x112 by a UQ112x112, returning a UQ112x112
function divuq(uq112x112 memory self, uq112x112 memory other) internal pure returns (uq112x112 memory) {
require(other._x > 0, 'FixedPoint::divuq: division by zero');
if (self._x == other._x) {
return uq112x112(uint224(Q112));
}
if (self._x <= uint144(-1)) {
uint256 value = (uint256(self._x) << RESOLUTION) / other._x;
require(value <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(value));
}
uint256 result = FullMath.mulDiv(Q112, self._x, other._x);
require(result <= uint224(-1), 'FixedPoint::divuq: overflow');
return uq112x112(uint224(result));
}
// returns a UQ112x112 which represents the ratio of the numerator to the denominator
// can be lossy
function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) {
require(denominator > 0, 'FixedPoint::fraction: division by zero');
if (numerator == 0) return FixedPoint.uq112x112(0);
if (numerator <= uint144(-1)) {
uint256 result = (numerator << RESOLUTION) / denominator;
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
} else {
uint256 result = FullMath.mulDiv(numerator, Q112, denominator);
require(result <= uint224(-1), 'FixedPoint::fraction: overflow');
return uq112x112(uint224(result));
}
}
// take the reciprocal of a UQ112x112
// reverts on overflow
// lossy
function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) {
require(self._x != 0, 'FixedPoint::reciprocal: reciprocal of zero');
require(self._x != 1, 'FixedPoint::reciprocal: overflow');
return uq112x112(uint224(Q224 / self._x));
}
// square root of a UQ112x112
// lossy between 0/1 and 40 bits
function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) {
if (self._x <= uint144(-1)) {
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << 112)));
}
uint8 safeShiftBits = 255 - BitMath.mostSignificantBit(self._x);
safeShiftBits -= safeShiftBits % 2;
return uq112x112(uint224(Babylonian.sqrt(uint256(self._x) << safeShiftBits) << ((112 - safeShiftBits) / 2)));
}
}
// File: contracts/lib/IUniswapV2Pair.sol
pragma solidity 0.6.5;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: @openzeppelin/contracts/math/SafeMath.sol
// 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, 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: contracts/lib/UniswapV2Library.sol
pragma solidity 0.6.5;
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
// File: contracts/lib/IUniswapV2Factory.sol
pragma solidity 0.6.5;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// File: contracts/lib/UniswapV2OracleLibrary.sol
pragma solidity 0.6.5;
// library with helper methods for oracles that are concerned with computing average prices
library UniswapV2OracleLibrary {
using FixedPoint for *;
// helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1]
function currentBlockTimestamp() internal view returns (uint32) {
return uint32(block.timestamp % 2 ** 32);
}
// produces the cumulative price using counterfactuals to save gas and avoid a call to sync.
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
// if time has elapsed since the last update on the pair, mock the accumulated price values
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
// subtraction overflow is desired
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
// addition overflow is desired
// counterfactual
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
// counterfactual
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/Oracle.sol
/*
___ _____ ___ _ _ _
( _`\ ( _ )( _`\ (_)( ) ( )
| (_) )| (_) || (_(_)| |`\`\/'/'
| _ <'| _ |`\__ \ | | > <
| (_) )| | | |( )_) || | /'/\`\
(____/'(_) (_)`\____)(_)(_) (_)
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.5;
// Some code reproduced from
// https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2Pair.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 OracleSimple {
using FixedPoint for *;
uint public PERIOD = 24 hours;
IUniswapV2Pair immutable pair;
address public immutable token0;
address public immutable token1;
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint32 public blockTimestampLast;
FixedPoint.uq112x112 public price0Average;
FixedPoint.uq112x112 public price1Average;
constructor(address factory, address tokenA, address tokenB) public {
IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.pairFor(factory, tokenA, tokenB));
pair = _pair;
token0 = _pair.token0();
token1 = _pair.token1();
price0CumulativeLast = _pair.price0CumulativeLast(); // fetch the current accumulated price value (1 / 0)
price1CumulativeLast = _pair.price1CumulativeLast(); // fetch the current accumulated price value (0 / 1)
uint112 reserve0;
uint112 reserve1;
(reserve0, reserve1, blockTimestampLast) = _pair.getReserves();
// ensure that there's liquidity in the pair
require(reserve0 != 0 && reserve1 != 0, 'OracleSimple: NO_RESERVES');
}
function update() internal {
(uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) =
UniswapV2OracleLibrary.currentCumulativePrices(address(pair));
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
// ensure that at least one full period has passed since the last update
require(timeElapsed >= PERIOD, 'OracleSimple: PERIOD_NOT_ELAPSED');
// overflow is desired, casting never truncates
// cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed
price0Average = FixedPoint.uq112x112(uint224((price0Cumulative - price0CumulativeLast) / timeElapsed));
price1Average = FixedPoint.uq112x112(uint224((price1Cumulative - price1CumulativeLast) / timeElapsed));
price0CumulativeLast = price0Cumulative;
price1CumulativeLast = price1Cumulative;
blockTimestampLast = blockTimestamp;
}
// note this will always return 0 before update has been called successfully for the first time.
function consult(address token, uint amountIn) internal view returns (uint amountOut) {
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
} else {
require(token == token1, 'OracleSimple: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
}
interface BasixTokenI {
function monetaryPolicy() external view returns (address);
}
contract BasixOracle is Ownable, OracleSimple, IOracle {
address basix;
uint256 constant SCALE = 10 ** 18;
address constant uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
constructor(address basix_, address susd_) public OracleSimple(uniFactory, basix_, susd_) {
PERIOD = 23 hours;
basix = basix_;
}
// this must be called 24h before first rebase to get proper price
function updateBeforeRebase() public onlyOwner {
update();
}
function getData() override external returns (uint256, bool) {
require(msg.sender == BasixTokenI(basix).monetaryPolicy());
update();
uint256 price = consult(basix, SCALE); // will return 1 BASIX in sUSD
if (price == 0) {
return (0, false);
}
return (price, true);
}
}
| note this will always return 0 before update has been called successfully for the first time. | function consult(address token, uint amountIn) internal view returns (uint amountOut) {
if (token == token0) {
amountOut = price0Average.mul(amountIn).decode144();
require(token == token1, 'OracleSimple: INVALID_TOKEN');
amountOut = price1Average.mul(amountIn).decode144();
}
}
| 5,468,718 | [
1,
7652,
333,
903,
3712,
327,
374,
1865,
1089,
711,
2118,
2566,
4985,
364,
326,
1122,
813,
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,
27710,
12,
2867,
1147,
16,
2254,
3844,
382,
13,
2713,
1476,
1135,
261,
11890,
3844,
1182,
13,
288,
203,
3639,
309,
261,
2316,
422,
1147,
20,
13,
288,
203,
5411,
3844,
1182,
273,
6205,
20,
17115,
18,
16411,
12,
8949,
382,
2934,
3922,
25339,
5621,
203,
5411,
2583,
12,
2316,
422,
1147,
21,
16,
296,
23601,
5784,
30,
10071,
67,
8412,
8284,
203,
5411,
3844,
1182,
273,
6205,
21,
17115,
18,
16411,
12,
8949,
382,
2934,
3922,
25339,
5621,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x11425C637ec3C121757264be6A8Cf26E47247450/sources/Pepe69.sol | 200 = 2x the above so 10% sell
| uint256 sellpercent = 100; | 2,707,417 | [
1,
6976,
273,
576,
92,
326,
5721,
1427,
1728,
9,
225,
357,
80,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
357,
80,
8849,
273,
2130,
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.4.25;
// File: contracts/saga/interfaces/IMintingPointTimersManager.sol
/**
* @title Minting Point Timers Manager Interface.
*/
interface IMintingPointTimersManager {
/**
* @dev Start a given timestamp.
* @param _id The ID of the timestamp.
* @notice When tested, this timestamp will be either 'running' or 'expired'.
*/
function start(uint256 _id) external;
/**
* @dev Reset a given timestamp.
* @param _id The ID of the timestamp.
* @notice When tested, this timestamp will be neither 'running' nor 'expired'.
*/
function reset(uint256 _id) external;
/**
* @dev Get an indication of whether or not a given timestamp is 'running'.
* @param _id The ID of the timestamp.
* @return An indication of whether or not a given timestamp is 'running'.
* @notice Even if this timestamp is not 'running', it is not necessarily 'expired'.
*/
function running(uint256 _id) external view returns (bool);
/**
* @dev Get an indication of whether or not a given timestamp is 'expired'.
* @param _id The ID of the timestamp.
* @return An indication of whether or not a given timestamp is 'expired'.
* @notice Even if this timestamp is not 'expired', it is not necessarily 'running'.
*/
function expired(uint256 _id) external view returns (bool);
}
// File: contracts/contract_address_locator/interfaces/IContractAddressLocator.sol
/**
* @title Contract Address Locator Interface.
*/
interface IContractAddressLocator {
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) external view returns (address);
/**
* @dev Determine whether or not a contract address relates to one of the identifiers.
* @param _contractAddress The contract address to look for.
* @param _identifiers The identifiers.
* @return A boolean indicating if the contract address relates to one of the identifiers.
*/
function isContractAddressRelates(address _contractAddress, bytes32[] _identifiers) external view returns (bool);
}
// File: contracts/contract_address_locator/ContractAddressLocatorHolder.sol
/**
* @title Contract Address Locator Holder.
* @dev Hold a contract address locator, which maps a unique identifier to every contract address in the system.
* @dev Any contract which inherits from this contract can retrieve the address of any contract in the system.
* @dev Thus, any contract can remain "oblivious" to the replacement of any other contract in the system.
* @dev In addition to that, any function in any contract can be restricted to a specific caller.
*/
contract ContractAddressLocatorHolder {
bytes32 internal constant _IAuthorizationDataSource_ = "IAuthorizationDataSource";
bytes32 internal constant _ISGNConversionManager_ = "ISGNConversionManager" ;
bytes32 internal constant _IModelDataSource_ = "IModelDataSource" ;
bytes32 internal constant _IPaymentHandler_ = "IPaymentHandler" ;
bytes32 internal constant _IPaymentManager_ = "IPaymentManager" ;
bytes32 internal constant _IPaymentQueue_ = "IPaymentQueue" ;
bytes32 internal constant _IReconciliationAdjuster_ = "IReconciliationAdjuster" ;
bytes32 internal constant _IIntervalIterator_ = "IIntervalIterator" ;
bytes32 internal constant _IMintHandler_ = "IMintHandler" ;
bytes32 internal constant _IMintListener_ = "IMintListener" ;
bytes32 internal constant _IMintManager_ = "IMintManager" ;
bytes32 internal constant _IPriceBandCalculator_ = "IPriceBandCalculator" ;
bytes32 internal constant _IModelCalculator_ = "IModelCalculator" ;
bytes32 internal constant _IRedButton_ = "IRedButton" ;
bytes32 internal constant _IReserveManager_ = "IReserveManager" ;
bytes32 internal constant _ISagaExchanger_ = "ISagaExchanger" ;
bytes32 internal constant _IMonetaryModel_ = "IMonetaryModel" ;
bytes32 internal constant _IMonetaryModelState_ = "IMonetaryModelState" ;
bytes32 internal constant _ISGAAuthorizationManager_ = "ISGAAuthorizationManager";
bytes32 internal constant _ISGAToken_ = "ISGAToken" ;
bytes32 internal constant _ISGATokenManager_ = "ISGATokenManager" ;
bytes32 internal constant _ISGNAuthorizationManager_ = "ISGNAuthorizationManager";
bytes32 internal constant _ISGNToken_ = "ISGNToken" ;
bytes32 internal constant _ISGNTokenManager_ = "ISGNTokenManager" ;
bytes32 internal constant _IMintingPointTimersManager_ = "IMintingPointTimersManager" ;
bytes32 internal constant _ITradingClasses_ = "ITradingClasses" ;
bytes32 internal constant _IWalletsTradingLimiterValueConverter_ = "IWalletsTLValueConverter" ;
bytes32 internal constant _IWalletsTradingDataSource_ = "IWalletsTradingDataSource" ;
bytes32 internal constant _WalletsTradingLimiter_SGNTokenManager_ = "WalletsTLSGNTokenManager" ;
bytes32 internal constant _WalletsTradingLimiter_SGATokenManager_ = "WalletsTLSGATokenManager" ;
bytes32 internal constant _IETHConverter_ = "IETHConverter" ;
bytes32 internal constant _ITransactionLimiter_ = "ITransactionLimiter" ;
bytes32 internal constant _ITransactionManager_ = "ITransactionManager" ;
bytes32 internal constant _IRateApprover_ = "IRateApprover" ;
IContractAddressLocator private contractAddressLocator;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
*/
constructor(IContractAddressLocator _contractAddressLocator) internal {
require(_contractAddressLocator != address(0), "locator is illegal");
contractAddressLocator = _contractAddressLocator;
}
/**
* @dev Get the contract address locator.
* @return The contract address locator.
*/
function getContractAddressLocator() external view returns (IContractAddressLocator) {
return contractAddressLocator;
}
/**
* @dev Get the contract address mapped to a given identifier.
* @param _identifier The identifier.
* @return The contract address.
*/
function getContractAddress(bytes32 _identifier) internal view returns (address) {
return contractAddressLocator.getContractAddress(_identifier);
}
/**
* @dev Determine whether or not the sender relates to one of the identifiers.
* @param _identifiers The identifiers.
* @return A boolean indicating if the sender relates to one of the identifiers.
*/
function isSenderAddressRelates(bytes32[] _identifiers) internal view returns (bool) {
return contractAddressLocator.isContractAddressRelates(msg.sender, _identifiers);
}
/**
* @dev Verify that the caller is mapped to a given identifier.
* @param _identifier The identifier.
*/
modifier only(bytes32 _identifier) {
require(msg.sender == getContractAddress(_identifier), "caller is illegal");
_;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: contracts/saga/MintingPointTimersManager.sol
/**
* Details of usage of licenced software see here: https://www.saga.org/software/readme_v1
*/
/**
* @title Minting Point Timers Manager.
*/
contract MintingPointTimersManager is IMintingPointTimersManager, ContractAddressLocatorHolder {
string public constant VERSION = "1.0.0";
using SafeMath for uint256;
struct Timestamp {
bool valid;
uint256 value;
}
uint256 public timeout;
Timestamp[105] public timestamps;
/**
* @dev Create the contract.
* @param _contractAddressLocator The contract address locator.
* @param _timeout The number of seconds elapsed between 'running' and 'expired'.
* @notice Each timestamp can be in either one of 3 states: 'running', 'expired' or 'invalid'.
*/
constructor(IContractAddressLocator _contractAddressLocator, uint256 _timeout) ContractAddressLocatorHolder(_contractAddressLocator) public {
timeout = _timeout;
}
/**
* @dev Start a given timestamp.
* @param _id The ID of the timestamp.
* @notice When tested, this timestamp will be either 'running' or 'expired'.
*/
function start(uint256 _id) external only(_IIntervalIterator_) {
Timestamp storage timestamp = timestamps[_id];
assert(!timestamp.valid);
timestamp.valid = true;
timestamp.value = time();
}
/**
* @dev Reset a given timestamp.
* @param _id The ID of the timestamp.
* @notice When tested, this timestamp will be neither 'running' nor 'expired'.
*/
function reset(uint256 _id) external only(_IIntervalIterator_) {
Timestamp storage timestamp = timestamps[_id];
assert(timestamp.valid);
timestamp.valid = false;
timestamp.value = 0;
}
/**
* @dev Get an indication of whether or not a given timestamp is 'running'.
* @param _id The ID of the timestamp.
* @return An indication of whether or not a given timestamp is 'running'.
* @notice Even if this timestamp is not 'running', it is not necessarily 'expired'.
*/
function running(uint256 _id) external view returns (bool) {
Timestamp storage timestamp = timestamps[_id];
if (!timestamp.valid)
return false;
return timestamp.value.add(timeout) >= time();
}
/**
* @dev Get an indication of whether or not a given timestamp is 'expired'.
* @param _id The ID of the timestamp.
* @return An indication of whether or not a given timestamp is 'expired'.
* @notice Even if this timestamp is not 'expired', it is not necessarily 'running'.
*/
function expired(uint256 _id) external view returns (bool) {
Timestamp storage timestamp = timestamps[_id];
if (!timestamp.valid)
return false;
return timestamp.value.add(timeout) < time();
}
/**
* @dev Return the current time (equivalent to `block.timestamp`).
* @notice This function can be overridden in order to perform artificial time-simulation.
*/
function time() internal view returns (uint256) {
return now;
}
}
| * @dev Get an indication of whether or not a given timestamp is 'running'. @param _id The ID of the timestamp. @return An indication of whether or not a given timestamp is 'running'. @notice Even if this timestamp is not 'running', it is not necessarily 'expired'./ | function running(uint256 _id) external view returns (bool) {
Timestamp storage timestamp = timestamps[_id];
if (!timestamp.valid)
return false;
return timestamp.value.add(timeout) >= time();
}
| 7,287,903 | [
1,
967,
392,
1547,
829,
434,
2856,
578,
486,
279,
864,
2858,
353,
296,
8704,
10332,
225,
389,
350,
1021,
1599,
434,
326,
2858,
18,
327,
1922,
1547,
829,
434,
2856,
578,
486,
279,
864,
2858,
353,
296,
8704,
10332,
225,
25067,
309,
333,
2858,
353,
486,
296,
8704,
2187,
518,
353,
486,
23848,
296,
15820,
10332,
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,
3549,
12,
11890,
5034,
389,
350,
13,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
8159,
2502,
2858,
273,
11267,
63,
67,
350,
15533,
203,
3639,
309,
16051,
5508,
18,
877,
13,
203,
5411,
327,
629,
31,
203,
3639,
327,
2858,
18,
1132,
18,
1289,
12,
4538,
13,
1545,
813,
5621,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interface/IMFNFT.sol";
import "./interface/IERC721.sol";
import "./math/SafeMath.sol";
import "./helper/Verifier.sol";
/**
* @title TWIG_FNFT Contract
*/
contract MFNFT is IMFNFT, Verifier {
using SafeMath for uint256;
mapping(uint256 => mapping(address => uint256)) private _balances;
mapping(uint256 => mapping(address => mapping(address => uint256)))
private _allowed;
// uint256 private _totalSupply;
mapping(uint256 => uint256) _totalSupply;
// NFT Contract Address
// address private _parentToken;
mapping(uint256 => address) _parentToken;
// NFT ID of NFT(RFT) - TokenId
// uint256 private _parentTokenId;
mapping(uint256 => uint256) _parentTokenId;
//
mapping(address => mapping(uint256 => uint256)) private _Ids;
// Scalar value to distinguish fractionalized NFT
uint256 public _id;
// Admin Address to Set the Parent NFT
address private _admin;
// Event emitted when token is added
event TokenAddition(
address indexed token,
uint256 tokenId,
uint256 _id,
uint256 totalSupply
);
constructor() {
_admin = msg.sender;
}
/**
* @dev onlyAdmin prohibits function calls arbitrary msg.sender
* except _admin
*/
modifier onlyAdmin() {
require(msg.sender == _admin);
_;
}
/**
* @dev Mandatory function to receive NFT as a contract(CA)
* @return Bytes4 which is the selector of this function
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes calldata _data
) external pure returns (bytes4) {
return this.onERC721Received.selector;
}
/**
* @dev (ERC165) Determines if this contract supports Re-FT(ERC1633).
* @param interfaceID The bytes4 to query if it matches with the contract interface id.
*/
function supportsInterface(bytes4 interfaceID)
external
pure
returns (bool)
{
return
interfaceID == this.supportsInterface.selector || // ERC165
interfaceID == this.parentToken.selector || // parentToken()
interfaceID == this.parentTokenId.selector || // parentTokenId()
interfaceID ==
this.parentToken.selector ^ this.parentTokenId.selector; // RFT
}
/**
* @dev Sets the Address of NFT Contract Address & NFT Token ID
* @param parentNFTContractAddress The address NFT Contract address.
* @param parentNFTTokenId The token id of NFT.
*/
function setParentNFT(
address parentNFTContractAddress,
uint256 parentNFTTokenId,
uint256 totalSupply
) public onlyAdmin {
require(
parentNFTContractAddress != address(0),
"MFNFT::setParentNFT: Parent NFT Contract should not be zero"
);
require(
getTokenId(parentNFTContractAddress, parentNFTTokenId) == 0,
"MFNFT::setParentNFT: Already owned(fractionalized) by this contract"
);
verifyOwnership(parentNFTContractAddress, parentNFTTokenId);
_id++;
_Ids[parentNFTContractAddress][parentNFTTokenId] = _id;
_parentToken[_id] = parentNFTContractAddress;
_parentTokenId[_id] = parentNFTTokenId;
_totalSupply[_id] = totalSupply;
_balances[_id][msg.sender] = totalSupply;
emit TokenAddition(
parentNFTContractAddress,
parentNFTTokenId,
_id,
totalSupply
);
}
/**
* @dev Returns the tokenId of with the given NFT information
* @return An uint256 value representing the tokenId of given NFT
*/
function getTokenId(address token, uint256 tokenId)
public
view
returns (uint256)
{
return _Ids[token][tokenId];
}
/**
* @dev Returns if the NFT is owned(fractionalized) by this contract.
* @return An bool representing whether the NFT is fractionalized by this contract
*/
function isRegistered(address token, uint256 tokenId) public view returns (bool) {
return (_Ids[token][tokenId] != 0);
}
/**
* @dev Returns the Address of Parent Token Address
* @return An Address representing the address of NFT Contract this Re-FT is pointing to.
*/
function parentToken(uint256 tokenId) external view returns (address) {
return _parentToken[tokenId];
}
/**
* @dev Returns the Token ID of NFT
* @return An uint256 representing the token id of the NFT this Re-FT is pointing to.
*/
function parentTokenId(uint256 tokenId) external view returns (uint256) {
return _parentTokenId[tokenId];
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply(uint256 tokenId)
public
view
override
returns (uint256)
{
return _totalSupply[tokenId];
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner, uint256 tokenId)
public
view
override
returns (uint256)
{
return _balances[tokenId][owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender,
uint256 tokenId
) public view override returns (uint256) {
return _allowed[tokenId][owner][spender];
}
/**
* @dev Transfer token for a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(
address to,
uint256 tokenId,
uint256 value
) public override returns (bool) {
_transfer(msg.sender, to, tokenId, 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 tokenId,
uint256 value
) public override returns (bool) {
require(spender != address(0));
_allowed[tokenId][msg.sender][spender] = value;
emit Approval(msg.sender, spender, tokenId, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address from,
address to,
uint256 tokenId,
uint256 value
) public override returns (bool) {
_allowed[tokenId][from][msg.sender] = _allowed[tokenId][from][
msg.sender
].sub(value);
_transfer(from, to, tokenId, value);
emit Approval(
from,
msg.sender,
tokenId,
_allowed[tokenId][from][msg.sender]
);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 tokenId,
uint256 addedValue
) public returns (bool) {
require(spender != address(0));
_allowed[tokenId][msg.sender][spender] = _allowed[tokenId][msg.sender][
spender
].add(addedValue);
emit Approval(
msg.sender,
spender,
tokenId,
_allowed[tokenId][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
* Emits an Approval event.
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 tokenId,
uint256 subtractedValue
) public returns (bool) {
require(spender != address(0));
_allowed[tokenId][msg.sender][spender] = _allowed[tokenId][msg.sender][
spender
].sub(subtractedValue);
emit Approval(
msg.sender,
spender,
tokenId,
_allowed[tokenId][msg.sender][spender]
);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(
address from,
address to,
uint256 tokenId,
uint256 value
) internal {
require(to != address(0));
_balances[tokenId][from] = _balances[tokenId][from].sub(value);
_balances[tokenId][to] = _balances[tokenId][to].add(value);
emit Transfer(from, to, tokenId, value);
}
}
| * @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 Emits an Approval event. @param spender The address which will spend the funds. @param addedValue The amount of tokens to increase the allowance by./ | function increaseAllowance(
address spender,
uint256 tokenId,
uint256 addedValue
) public returns (bool) {
require(spender != address(0));
_allowed[tokenId][msg.sender][spender] = _allowed[tokenId][msg.sender][
spender
].add(addedValue);
emit Approval(
msg.sender,
spender,
tokenId,
_allowed[tokenId][msg.sender][spender]
);
return true;
}
| 12,921,272 | [
1,
382,
11908,
326,
3844,
434,
2430,
716,
392,
3410,
2935,
358,
279,
17571,
264,
18,
6617,
537,
1410,
506,
2566,
1347,
2935,
67,
63,
67,
87,
1302,
264,
65,
422,
374,
18,
2974,
5504,
2935,
460,
353,
7844,
358,
999,
333,
445,
358,
4543,
576,
4097,
261,
464,
2529,
3180,
326,
1122,
2492,
353,
1131,
329,
13,
6338,
9041,
355,
483,
18485,
3155,
18,
18281,
7377,
1282,
392,
1716,
685,
1125,
871,
18,
225,
17571,
264,
1021,
1758,
1492,
903,
17571,
326,
284,
19156,
18,
225,
3096,
620,
1021,
3844,
434,
2430,
358,
10929,
326,
1699,
1359,
635,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10929,
7009,
1359,
12,
203,
3639,
1758,
17571,
264,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
2254,
5034,
3096,
620,
203,
565,
262,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
87,
1302,
264,
480,
1758,
12,
20,
10019,
203,
203,
3639,
389,
8151,
63,
2316,
548,
6362,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
389,
8151,
63,
2316,
548,
6362,
3576,
18,
15330,
6362,
203,
5411,
17571,
264,
203,
3639,
308,
18,
1289,
12,
9665,
620,
1769,
203,
203,
3639,
3626,
1716,
685,
1125,
12,
203,
5411,
1234,
18,
15330,
16,
203,
5411,
17571,
264,
16,
203,
5411,
1147,
548,
16,
203,
5411,
389,
8151,
63,
2316,
548,
6362,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
203,
3639,
11272,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
// NFT contract to inherit from.
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
// Helper functions OpenZeppelin provides.
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "hardhat/console.sol";
// Helper we wrote to encode in Base64
import "./Base64.sol";
/// @title Redwall
/// @author Andreas Bigger <[email protected]>
/// @notice An ERC721 turn-based mini-game built for the Buildspace NFT Game Alkes Cohort
contract Redwar is ERC721 {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
/// @notice The attributes of our characters
struct CharacterAttributes {
uint256 characterIndex;
string name;
string imageURI;
uint256 hp;
uint256 maxHp;
uint256 attackDamage;
}
/// @notice previous time Boss Healed
uint256 public previousBossHealing;
/// @dev Honorary tokens for minting when characters die
Counters.Counter private _honoraryTokenIds;
/// @dev Maximum honorary token id
uint256 private _maxHonoryTokenId;
/// @notice A list of characters
CharacterAttributes[] public defaultCharacters;
/// @dev price + developmentFee = 0.02 ether
uint256 public price = 0.018 ether;
uint256 public developmentFee = 0.002 ether;
/// @notice Mapping from nft tokenId => attributes.
mapping(uint256 => CharacterAttributes) public nftHolderAttributes;
/// @dev developer
address private developer;
/// @notice The Evolving Redwall BigBoss
struct BigBoss {
string name;
string imageURI;
uint256 level;
uint256 hp;
uint256 maxHp;
uint256 attackDamage;
}
BigBoss public bigBoss;
/// @notice Mapping from address => tokenId
/// @dev Lazy way of quickly referencing an owner's token id
mapping(address => uint256) public nftHolders;
/* -------------------------- *
* EVENTS *
* -------------------------- */
/// @notice Emitted when a Character is minted by a user
event CharacterNFTMinted(uint256 indexed tokenId, address sender, uint256 characterIndex);
/// @notice Emitted when a Character finised attacking the BigBoss
event AttackComplete(uint newBossHp, uint newPlayerHp);
/// @notice Emitted when the BigBoss dies and is reincarnated
event BossUpgraded(uint256 indexed level, address conqueror, uint256 maxHp, uint256 attackDamage);
/// @notice Character Dies
event CharacterDied(uint256 indexed tokenId, address owner);
/// @notice Honorary token minted
event HonoraryMint(uint256 indexed nextHonoraryToken, address owner, uint256 _characterIndex);
constructor(
string[] memory characterNames,
string[] memory characterImageURIs,
uint256[] memory characterHp,
uint256[] memory characterAttackDmg,
string memory bossName,
string memory bossImageURI,
uint256 bossHp,
uint256 bossAttackDamage,
uint256 maximumHonoraryTokenId,
address _developer
)
ERC721("Redwar", "RWAR")
{
bigBoss = BigBoss({
name: bossName,
imageURI: bossImageURI,
level: 0,
hp: bossHp,
maxHp: bossHp,
attackDamage: bossAttackDamage
});
for (uint256 i = 0; i < characterNames.length; i += 1) {
defaultCharacters.push(
CharacterAttributes({
characterIndex: i,
name: characterNames[i],
imageURI: characterImageURIs[i],
hp: characterHp[i],
maxHp: characterHp[i],
attackDamage: characterAttackDmg[i]
})
);
CharacterAttributes memory c = defaultCharacters[i];
}
// We want to increase the general tokenIds to above the honorary set
for (uint256 x = 0; x <= maximumHonoraryTokenId; x += 1) {
_tokenIds.increment();
}
// Set the maximum id of the honorary token set
_maxHonoryTokenId = maximumHonoraryTokenId;
// Increment so we always start at 1 :)
_honoraryTokenIds.increment();
// Set the developer
developer = _developer;
}
/// @notice Heals the boss
function healBoss() public {
// Check last block update for boss health and try to increase
if(block.timestamp - previousBossHealing > 43_200) {
// we are past a day and can give the boss a break
if(bigBoss.hp + 10 < bigBoss.maxHp) {
bigBoss.hp = bigBoss.hp + 10;
previousBossHealing = block.timestamp;
}
}
}
/// @notice Function to attack the Big Boss
function attackBoss() public {
// CHECKS
// Try and heal boss
healBoss();
// TODO: prevent reentrency bug here since player can hit the big boss for damage multiple times
// while their player storage only gets updated once (overwritten)
// Get the state of the player's NFT.
uint256 nftTokenIdOfPlayer = nftHolders[msg.sender];
CharacterAttributes storage player = nftHolderAttributes[nftTokenIdOfPlayer];
// Make sure the player has more than 0 HP.
require (
player.hp > 0,
"CHARACTER_HAS_NO_HEALTH"
);
// Allow player to attack boss.
if (bigBoss.hp < player.attackDamage) {
bigBoss.hp = 0;
// EFFECTS
// Now we upgrade the boss
bigBoss.level = bigBoss.level + 1;
bigBoss.maxHp = bigBoss.maxHp * 2;
bigBoss.hp = bigBoss.maxHp;
bigBoss.attackDamage = bigBoss.attackDamage + 5;
emit BossUpgraded(bigBoss.level, msg.sender, bigBoss.maxHp, bigBoss.attackDamage);
// INTERACTIONS
// Transfer reward to user
payable(msg.sender).call{value: address(this).balance}("");
} else {
bigBoss.hp = bigBoss.hp - player.attackDamage;
}
// Allow boss to attack player.
if (player.hp < bigBoss.attackDamage) {
player.hp = 0;
emit CharacterDied(nftTokenIdOfPlayer, msg.sender);
// Get current honorary token id (starts at 1 since we incremented in the constructor).
uint256 nextHonoraryToken = _honoraryTokenIds.current();
// Check if we can mint them an honorary token (:
if(nextHonoraryToken <= _maxHonoryTokenId) {
// MINT
_safeMint(msg.sender, nextHonoraryToken);
// choose the character using the index
uint256 _characterIndex = nextHonoraryToken % defaultCharacters.length;
// Store tokenId to character attributes mapping
nftHolderAttributes[nextHonoraryToken] = CharacterAttributes({
characterIndex: _characterIndex,
name: defaultCharacters[_characterIndex].name,
imageURI: defaultCharacters[_characterIndex].imageURI,
hp: defaultCharacters[_characterIndex].hp,
maxHp: defaultCharacters[_characterIndex].hp,
attackDamage: defaultCharacters[_characterIndex].attackDamage
});
// Keep an easy way to see who owns what NFT.
nftHolders[msg.sender] = nextHonoraryToken;
// Increment the _honoraryTokenIds for the next person that uses it.
_honoraryTokenIds.increment();
emit HonoraryMint(nextHonoraryToken, msg.sender, _characterIndex);
}
} else {
player.hp = player.hp - bigBoss.attackDamage;
}
emit AttackComplete(bigBoss.hp, player.hp);
}
function checkIfUserHasNFT() public view returns (CharacterAttributes memory) {
// Get the tokenId of the user's character NFT
uint256 userNftTokenId = nftHolders[msg.sender];
// If the user has a tokenId in the map, return their character.
if (userNftTokenId > 0) {
return nftHolderAttributes[userNftTokenId];
}
// Else, return an empty character.
else {
CharacterAttributes memory emptyStruct;
return emptyStruct;
}
}
/// @notice Return the list of Characters
function getAllDefaultCharacters() public view returns (CharacterAttributes[] memory) {
return defaultCharacters;
}
/// @notice gets the BigBoss
/// @return BigBoss
function getBigBoss() public view returns (BigBoss memory) {
return bigBoss;
}
/// @notice mints a user an NFT
/// @param _characterIndex the specific character to mint
function mintCharacterNFT(uint256 _characterIndex) external payable {
// CHECKS
healBoss(); // Try and heal boss first
require(msg.value >= price + developmentFee, "PRICE_NOT_MET");
require(_characterIndex < defaultCharacters.length, "CHARACTER_NON_EXISTANT");
// Get current tokenId (starts at 1 since we incremented in the constructor).
uint256 newItemId = _tokenIds.current();
// The magical function! Assigns the tokenId to the caller's wallet address.
_safeMint(msg.sender, newItemId);
// Try to send fee to developooor
payable(developer).call{value: developmentFee}("");
// We map the tokenId => their character attributes. More on this in
// the lesson below.
nftHolderAttributes[newItemId] = CharacterAttributes({
characterIndex: _characterIndex,
name: defaultCharacters[_characterIndex].name,
imageURI: defaultCharacters[_characterIndex].imageURI,
hp: defaultCharacters[_characterIndex].hp,
maxHp: defaultCharacters[_characterIndex].hp,
attackDamage: defaultCharacters[_characterIndex].attackDamage
});
// Keep an easy way to see who owns what NFT.
nftHolders[msg.sender] = newItemId;
// Increment the tokenId for the next person that uses it.
_tokenIds.increment();
emit CharacterNFTMinted(newItemId, msg.sender, _characterIndex);
}
/// @notice The meat and potatoes returning the token metadata
/// @dev uses IPFS x Pinata X cloudflare to fetch the metada
/// @param _tokenId The token Id to fetch the URI for
/// @return a Base64 encoded string packed with the metadata
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
CharacterAttributes memory charAttributes = nftHolderAttributes[
_tokenId
];
string memory strHp = Strings.toString(charAttributes.hp);
string memory strMaxHp = Strings.toString(charAttributes.maxHp);
string memory strAttackDamage = Strings.toString(charAttributes.attackDamage);
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
'{"name": "',
charAttributes.name,
' -- NFT #: ',
Strings.toString(_tokenId),
'", "description": "An epic NFT", "image": "ipfs://',
charAttributes.imageURI,
'", "attributes": [ { "trait_type": "Health Points", "value": ',strHp,', "max_value":',strMaxHp,'}, { "trait_type": "Attack Damage", "value": ',
strAttackDamage,'} ]}'
)
)
)
);
string memory output = string(
abi.encodePacked("data:application/json;base64,", json)
);
return output;
}
}
| @dev Honorary tokens for minting when characters die | Counters.Counter private _honoraryTokenIds;
| 5,461,185 | [
1,
44,
265,
280,
814,
2430,
364,
312,
474,
310,
1347,
3949,
10387,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9354,
87,
18,
4789,
3238,
389,
76,
265,
280,
814,
1345,
2673,
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
] |
./partial_match/1/0x7DE83EB89eE6E5506f3C9221c5371D536d442000/sources/XchangeRouterV2.sol | given some amount of an asset and pair reserves, returns an equivalent amount of the other asset | function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'XchangeLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'XchangeLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA * reserveB / reserveA;
}
| 15,745,826 | [
1,
10822,
2690,
3844,
434,
392,
3310,
471,
3082,
400,
264,
3324,
16,
1135,
392,
7680,
3844,
434,
326,
1308,
3310,
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,
3862,
12,
11890,
3844,
37,
16,
2254,
20501,
37,
16,
2254,
20501,
38,
13,
2713,
16618,
1135,
261,
11890,
3844,
38,
13,
288,
203,
3639,
2583,
12,
8949,
37,
405,
374,
16,
296,
60,
3427,
9313,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
2192,
51,
5321,
8284,
203,
3639,
2583,
12,
455,
6527,
37,
405,
374,
597,
20501,
38,
405,
374,
16,
296,
60,
3427,
9313,
30,
2120,
6639,
42,
1653,
7266,
2222,
67,
2053,
53,
3060,
4107,
8284,
203,
3639,
3844,
38,
273,
3844,
37,
380,
20501,
38,
342,
20501,
37,
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
] |
./full_match/56/0x6Df6a43Be4B706c45BC028D652829299D932d000/sources/juryProject.sol | this is the decimals of the rewards percent, (for example: 2 = 0.02, 3 = 0.002) "the number of zeros".
| uint256 rewardPercentDecimal; | 3,235,512 | [
1,
2211,
353,
326,
15105,
434,
326,
283,
6397,
5551,
16,
261,
1884,
3454,
30,
576,
273,
374,
18,
3103,
16,
890,
273,
374,
18,
24908,
13,
315,
5787,
1300,
434,
4922,
9654,
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,
3639,
2254,
5034,
19890,
8410,
5749,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@nibbstack/erc721/src/contracts/tokens/nf-token.sol";
import "@nibbstack/erc721/src/contracts/ownership/ownable.sol";
import {ERC20Spendable} from "./AriaToken.sol";
/**
* @notice A non-fungible certificate that anybody can create by spending tokens
*/
contract AriaCertificate is NFToken, Ownable
{
/// @notice The price to create new certificates
uint256 _mintingPrice;
/// @notice The currency to create new certificates
ERC20Spendable _mintingCurrency;
/// @dev The serial number of the next certificate to create
uint256 nextCertificateId = 1;
mapping(uint256 => bytes32) certificateDataHashes;
/**
* @notice Query the certificate hash for a token
* @param tokenId Which certificate to query
* @return The hash for the certificate
*/
function hashForToken(uint256 tokenId) external view returns (bytes32) {
return certificateDataHashes[tokenId];
}
/**
* @notice The price to create certificates
* @return The price to create certificates
*/
function mintingPrice() external view returns (uint256) {
return _mintingPrice;
}
/**
* @notice The currency (ERC20) to create certificates
* @return The currency (ERC20) to create certificates
*/
function mintingCurrency() external view returns (ERC20Spendable) {
return _mintingCurrency;
}
/**
* @notice Set new price to create certificates
* @param newMintingPrice The new price
*/
function setMintingPrice(uint256 newMintingPrice) onlyOwner external {
_mintingPrice = newMintingPrice;
}
/**
* @notice Set new ERC20 currency to create certificates
* @param newMintingCurrency The new currency
*/
function setMintingCurrency(ERC20Spendable newMintingCurrency) onlyOwner external {
_mintingCurrency = newMintingCurrency;
}
/**
* @notice Allows anybody to create a certificate, takes payment from the
* msg.sender
* @param dataHash A representation of the certificate data using the Aria
* protocol (a 0xcert cenvention).
* @return The new certificate ID
*
*/
function create(bytes32 dataHash) external returns (uint) {
// Take payment for this service
_mintingCurrency.spend(_mintingPrice);
// Create the certificate
uint256 newCertificateId = nextCertificateId;
_mint(msg.sender, newCertificateId);
certificateDataHashes[newCertificateId] = dataHash;
nextCertificateId = nextCertificateId + 1;
return newCertificateId;
}
} | @notice The price to create new certificates @notice The currency to create new certificates @dev The serial number of the next certificate to create* @notice Query the certificate hash for a token @param tokenId Which certificate to query @return The hash for the certificate/ | function hashForToken(uint256 tokenId) external view returns (bytes32) {
return certificateDataHashes[tokenId];
}
| 1,803,893 | [
1,
1986,
6205,
358,
752,
394,
12522,
225,
1021,
5462,
358,
752,
394,
12522,
225,
1021,
2734,
1300,
434,
326,
1024,
4944,
358,
752,
225,
2770,
326,
4944,
1651,
364,
279,
1147,
225,
1147,
548,
21918,
4944,
358,
843,
327,
1021,
1651,
364,
326,
4944,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1651,
1290,
1345,
12,
11890,
5034,
1147,
548,
13,
3903,
1476,
1135,
261,
3890,
1578,
13,
288,
203,
3639,
327,
4944,
751,
14455,
63,
2316,
548,
15533,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/0xE2d593ee1018C6BeEADc3415316EEf1084061aB1/sources/src/Nibble.sol | @notice Only owner function to remove excluded addresses from the tax @param _addrs - The addresses to remove from the excluded list | function removeExcludedAddrsFromTax(address[] calldata _addrs) external onlyOwner {
for (uint256 i = 0; i < _addrs.length; i++) {
require(_addrs[i] != multiSigWallet, "NIBBLE: Cannot remove multiSigWallet from excluded list");
require(_addrs[i] != address(0), "NIBBLE: Address cannot be zero");
addrsExcludedFromTax[_addrs[i]] = false;
}
}
| 8,395,038 | [
1,
3386,
3410,
445,
358,
1206,
8845,
6138,
628,
326,
5320,
225,
389,
23305,
300,
1021,
6138,
358,
1206,
628,
326,
8845,
666,
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,
1206,
16461,
13811,
1265,
7731,
12,
2867,
8526,
745,
892,
389,
23305,
13,
3903,
1338,
5541,
288,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
389,
23305,
18,
2469,
31,
277,
27245,
288,
203,
1377,
2583,
24899,
23305,
63,
77,
65,
480,
3309,
8267,
16936,
16,
315,
50,
45,
9676,
900,
30,
14143,
1206,
3309,
8267,
16936,
628,
8845,
666,
8863,
203,
1377,
2583,
24899,
23305,
63,
77,
65,
480,
1758,
12,
20,
3631,
315,
50,
45,
9676,
900,
30,
5267,
2780,
506,
3634,
8863,
203,
1377,
11755,
16461,
1265,
7731,
63,
67,
23305,
63,
77,
13563,
273,
629,
31,
203,
565,
289,
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
] |
./full_match/42/0x250bEb9F4da144e652DdCc0057805F62142540d3/sources/Users/ovdbigge/react/zknukes/contracts/sidechain/game/GameBase.sol | `msg.sender.transfer(_wei)` should be avoided, see https:diligence.consensys.net/blog/2019/09/stop-using-soliditys-transfer-now/ solium-disable-next-line security/no-call-value | function pushToken(address _token, uint256 _wei) internal {
if (_token == ETH_TOKEN_ADDRESS) {
require(success, "ETH transfer failed");
IERC20(_token).transfer(msg.sender, _wei);
}
}
| 16,213,678 | [
1,
68,
3576,
18,
15330,
18,
13866,
24899,
1814,
77,
22025,
1410,
506,
1712,
11359,
785,
16,
2621,
2333,
30,
72,
330,
360,
802,
18,
8559,
773,
1900,
18,
2758,
19,
11439,
19,
6734,
29,
19,
5908,
19,
5681,
17,
9940,
17,
30205,
560,
87,
17,
13866,
17,
3338,
19,
3704,
5077,
17,
8394,
17,
4285,
17,
1369,
4373,
19,
2135,
17,
1991,
17,
1132,
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,
565,
445,
1817,
1345,
12,
2867,
389,
2316,
16,
2254,
5034,
389,
1814,
77,
13,
2713,
288,
203,
3639,
309,
261,
67,
2316,
422,
512,
2455,
67,
8412,
67,
15140,
13,
288,
203,
5411,
2583,
12,
4768,
16,
315,
1584,
44,
7412,
2535,
8863,
203,
5411,
467,
654,
39,
3462,
24899,
2316,
2934,
13866,
12,
3576,
18,
15330,
16,
389,
1814,
77,
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,
-100,
-100,
-100
] |
// File: browser/reserve.sol
// SPDX-License-Identifier: MIT
/*
_ __ __ ____ _ _____ ____ _ _ _
/ \ | \/ | _ \| | | ____/ ___| ___ | | __| | (_) ___
/ _ \ | |\/| | |_) | | | _|| | _ / _ \| |/ _` | | |/ _ \
/ ___ \| | | | __/| |___| |__| |_| | (_) | | (_| | _ | | (_) |
/_/ \_\_| |_|_| |_____|_____\____|\___/|_|\__,_| (_) |_|\___/
Ample Gold $AMPLG is a goldpegged defi protocol that is based on Ampleforths elastic tokensupply model.
AMPLG is designed to maintain its base price target of 0.01g of Gold with a progammed inflation adjustment (rebase).
Forked from Ampleforth Token-Geyser: https://github.com/ampleforth/token-geyser/ (Credits to Ampleforth team for implementation of rebasing on the ethereum network)
GPL 3.0 license
AMPLG_SunshineReserve.sol - AMPLG Sunshine Reserve - Staking Smart Contract
*/
// File: openzeppelin-solidity/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-solidity/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-solidity/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.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.
*
* 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 {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/IStaking.sol
pragma solidity 0.5.0;
/**
* @title Staking interface, as defined by EIP-900.
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-900.md
*/
contract IStaking {
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
function stake(uint256 amount, bytes calldata data) external;
function stakeFor(address user, uint256 amount, bytes calldata data) external;
function unstake(uint256 amount, bytes calldata data) external;
function totalStakedFor(address addr) public view returns (uint256);
function totalStaked() public view returns (uint256);
function token() external view returns (address);
/**
* @return False. This application does not support staking history.
*/
function supportsHistory() external pure returns (bool) {
return false;
}
}
// File: contracts/TokenPool.sol
pragma solidity 0.5.0;
/**
* @title A simple holder of tokens.
* This is a simple contract to hold tokens. It's useful in the case where a separate contract
* needs to hold multiple distinct pools of the same token.
*/
contract TokenPool is Ownable {
IERC20 public token;
constructor(IERC20 _token) public {
token = _token;
}
function balance() public view returns (uint256) {
return token.balanceOf(address(this));
}
function transfer(address to, uint256 value) external onlyOwner returns (bool) {
return token.transfer(to, value);
}
function rescueFunds(address tokenToRescue, address to, uint256 amount) external onlyOwner returns (bool) {
require(address(token) != tokenToRescue, 'TokenPool: Cannot claim token held by the contract');
return IERC20(tokenToRescue).transfer(to, amount);
}
}
// File: contracts/AMPLG_SunshineReserve.sol
pragma solidity 0.5.0;
/**
* @title AMPLG Sunshine Reserve
* @dev A smart-contract based mechanism to distribute tokens over time, inspired loosely by
* Compound and Uniswap.
*
*
* More background and motivation available at:
* https://github.com/ampleforth/RFCs/blob/master/RFCs/rfc-1.md
*/
contract AMPLGSunshineReserve is IStaking, Ownable {
using SafeMath for uint256;
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
// amount: Unlocked tokens, total: Total locked tokens
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
//
// Time-bonus params
//
uint256 public constant BONUS_DECIMALS = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
//
// Global accounting state
//
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
//
// User accounting state
//
// Represents a single stake for a user. A user may have multiple.
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
// Caches aggregated values from the User->Stake[] map to save computation.
// If lastAccountingTimestampSec is 0, there's no entry for that user.
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
// Aggregated staking values per user
mapping(address => UserTotals) private _userTotals;
// The collection of stakes for each user. Ordered by timestamp, earliest to latest.
mapping(address => Stake[]) private _userStakes;
//
// Locked/Unlocked Accounting state
//
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
/**
* @param stakingToken The token users deposit as stake.
* @param distributionToken The token users receive as they unstake.
* @param maxUnlockSchedules Max number of unlock stages, to guard against hitting gas limit.
* @param startBonus_ Starting time bonus, BONUS_DECIMALS fixed point.
* e.g. 25% means user gets 25% of max distribution tokens.
* @param bonusPeriodSec_ Length of time for bonus to increase linearly to max.
* @param initialSharesPerToken Number of shares to mint per staking token on first stake.
*/
constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules,
uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public {
// The start bonus must be some fraction of the max. (i.e. <= 100%)
require(startBonus_ <= 10**BONUS_DECIMALS, 'Sunshine Reserve: start bonus too high');
// If no period is desired, instead set startBonus = 100%
// and bonusPeriod to a small value like 1sec.
require(bonusPeriodSec_ != 0, 'Sunshine Reserve: bonus period is zero');
require(initialSharesPerToken > 0, 'Sunshine Reserve: initialSharesPerToken is zero');
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
/**
* @return The token users deposit as stake.
*/
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
/**
* @return The token users receive as they unstake.
*/
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
/**
* @dev Transfers amount of deposit tokens from the user.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stake(uint256 amount, bytes calldata data) external {
_stakeFor(msg.sender, msg.sender, amount);
}
/**
* @dev Transfers amount of deposit tokens from the caller on behalf of user.
* @param user User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
* @param data Not used.
*/
function stakeFor(address user, uint256 amount, bytes calldata data) external {
_stakeFor(msg.sender, user, amount);
}
/**
* @dev Private implementation of staking methods.
* @param staker User address who deposits tokens to stake.
* @param beneficiary User address who gains credit for this stake operation.
* @param amount Number of deposit tokens to stake.
*/
function _stakeFor(address staker, address beneficiary, uint256 amount) private {
require(amount > 0, 'Sunshine Reserve: stake amount is zero');
require(beneficiary != address(0), 'Sunshine Reserve: beneficiary is zero address');
require(totalStakingShares == 0 || totalStaked() > 0,
'Sunshine Reserve: Invalid state. Staking shares exist, but no staking tokens do');
uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
require(mintedStakingShares > 0, 'Sunshine Reserve: Stake amount is too small');
updateAccounting();
// 1. User Accounting
UserTotals storage totals = _userTotals[beneficiary];
totals.stakingShares = totals.stakingShares.add(mintedStakingShares);
totals.lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
// 2. Global Accounting
totalStakingShares = totalStakingShares.add(mintedStakingShares);
// Already set in updateAccounting()
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount),
'Sunshine Reserve: transfer into staking pool failed');
emit Staked(beneficiary, amount, totalStakedFor(beneficiary), "");
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @param data Not used.
*/
function unstake(uint256 amount, bytes calldata data) external {
_unstake(amount);
}
/**
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens that would be rewarded.
*/
function unstakeQuery(uint256 amount) public returns (uint256) {
return _unstake(amount);
}
/**
* @dev Unstakes a certain amount of previously deposited tokens. User also receives their
* alotted number of distribution tokens.
* @param amount Number of deposit tokens to unstake / withdraw.
* @return The total number of distribution tokens rewarded.
*/
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
// checks
require(amount > 0, 'Sunshine Reserve: unstake amount is zero');
require(totalStakedFor(msg.sender) >= amount,
'Sunshine Reserve: unstake amount is greater than total user stakes');
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked());
require(stakingSharesToBurn > 0, 'Sunshine Reserve: Unable to unstake amount this small');
// 1. User Accounting
UserTotals storage totals = _userTotals[msg.sender];
Stake[] storage accountStakes = _userStakes[msg.sender];
// Redeem from most recent stake and go backwards in time.
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
// fully redeem a past stake
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
accountStakes.length--;
} else {
// partially redeem a past stake
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// totals.lastAccountingTimestampSec = now;
// 2. Global Accounting
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
// Already set in updateAccounting
// _lastAccountingTimestampSec = now;
// interactions
require(_stakingPool.transfer(msg.sender, amount),
'Sunshine Reserve: transfer out of staking pool failed');
require(_unlockedPool.transfer(msg.sender, rewardAmount),
'Sunshine Reserve: transfer out of unlocked pool failed');
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
emit TokensClaimed(msg.sender, rewardAmount);
require(totalStakingShares == 0 || totalStaked() > 0,
"Sunshine Reserve: Error unstaking. Staking shares exist, but no staking tokens do");
return rewardAmount;
}
/**
* @dev Applies an additional time-bonus to a distribution amount. This is necessary to
* encourage long-term deposits instead of constant unstake/restakes.
* The bonus-multiplier is the result of a linear function that starts at startBonus and
* ends at 100% over bonusPeriodSec, then stays at 100% thereafter.
* @param currentRewardTokens The current number of distribution tokens already alotted for this
* unstake op. Any bonuses are already applied.
* @param stakingShareSeconds The stakingShare-seconds that are being burned for new
* distribution tokens.
* @param stakeTimeSec Length of time for which the tokens were staked. Needed to calculate
* the time-bonus.
* @return Updated amount of distribution tokens to award, with any bonus included on the
* newly added tokens.
*/
function computeNewReward(uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked()
.mul(stakingShareSeconds)
.div(_totalStakingShareSeconds);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**BONUS_DECIMALS;
uint256 bonusedReward =
startBonus
.add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec))
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
/**
* @param addr The user to look up staking information for.
* @return The number of staking tokens deposited for addr.
*/
function totalStakedFor(address addr) public view returns (uint256) {
return totalStakingShares > 0 ?
totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0;
}
/**
* @return The total number of deposit tokens staked globally, by all users.
*/
function totalStaked() public view returns (uint256) {
return _stakingPool.balance();
}
/**
* @dev Note that this application has a staking token as well as a distribution token, which
* may be different. This function is required by EIP-900.
* @return The deposit token used for staking.
*/
function token() external view returns (address) {
return address(getStakingToken());
}
/**
* @dev A globally callable function to update the accounting state of the system.
* Global state and state for the caller are updated.
* @return [0] balance of the locked pool
* @return [1] balance of the unlocked pool
* @return [2] caller's staking share seconds
* @return [3] global staking share seconds
* @return [4] Rewards caller has accumulated, optimistically assumes max time-bonus.
* @return [5] block timestamp
*/
function updateAccounting() public returns (
uint256, uint256, uint256, uint256, uint256, uint256) {
unlockTokens();
// Global accounting
uint256 newStakingShareSeconds =
now
.sub(_lastAccountingTimestampSec)
.mul(totalStakingShares);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds);
_lastAccountingTimestampSec = now;
// User Accounting
UserTotals storage totals = _userTotals[msg.sender];
uint256 newUserStakingShareSeconds =
now
.sub(totals.lastAccountingTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserStakingShareSeconds);
totals.lastAccountingTimestampSec = now;
uint256 totalUserRewards = (_totalStakingShareSeconds > 0)
? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds)
: 0;
return (
totalLocked(),
totalUnlocked(),
totals.stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
/**
* @return Total number of locked distribution tokens.
*/
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
/**
* @return Total number of unlocked distribution tokens.
*/
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
/**
* @return Number of unlock schedules.
*/
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
/**
* @dev This funcion allows the contract owner to add more locked distribution tokens, along
* with the associated "unlock schedule". These locked tokens immediately begin unlocking
* linearly over the duraction of durationSec timeframe.
* @param amount Number of distribution tokens to lock. These are transferred from the caller.
* @param durationSec Length of time to linear unlock the tokens.
*/
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'Sunshine Reserve: reached maximum unlock schedules');
// Update lockedTokens amount before using it in computations after.
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'Sunshine Reserve: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
/**
* @dev Moves distribution tokens from the locked pool to the unlocked pool, according to the
* previously defined unlock schedules. Publicly callable.
* @return Number of newly unlocked distribution tokens.
*/
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
} else {
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'Sunshine Reserve: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
/**
* @dev Returns the number of unlockable shares from a given schedule. The returned value
* depends on the time since the last unlock. This function updates schedule accounting,
* but does not actually transfer any tokens.
* @param s Index of the unlock schedule.
* @return The number of unlocked shares.
*/
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if(schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
// Special case to handle any leftover dust from integer division
if (now >= schedule.endAtSec) {
sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));
schedule.lastUnlockTimestampSec = schedule.endAtSec;
} else {
sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
/**
* @dev Lets the owner rescue funds air-dropped to the staking pool.
* @param tokenToRescue Address of the token to be rescued.
* @param to Address to which the rescued funds are to be sent.
* @param amount Amount of tokens to be rescued.
* @return Transfer success.
*/
function rescueFundsFromStakingPool(address tokenToRescue, address to, uint256 amount)
public onlyOwner returns (bool) {
return _stakingPool.rescueFunds(tokenToRescue, to, amount);
}
} | More background and motivation available at:/ amount: Unlocked tokens, total: Total locked tokens Time-bonus params Global accounting state User accounting state Represents a single stake for a user. A user may have multiple. | contract AMPLGSunshineReserve is IStaking, Ownable {
using SafeMath for uint256;
event Staked(address indexed user, uint256 amount, uint256 total, bytes data);
event Unstaked(address indexed user, uint256 amount, uint256 total, bytes data);
event TokensClaimed(address indexed user, uint256 amount);
event TokensLocked(uint256 amount, uint256 durationSec, uint256 total);
event TokensUnlocked(uint256 amount, uint256 total);
TokenPool private _stakingPool;
TokenPool private _unlockedPool;
TokenPool private _lockedPool;
uint256 public constant BONUS_DECIMALS = 2;
uint256 public startBonus = 0;
uint256 public bonusPeriodSec = 0;
uint256 public totalLockedShares = 0;
uint256 public totalStakingShares = 0;
uint256 private _totalStakingShareSeconds = 0;
uint256 private _lastAccountingTimestampSec = now;
uint256 private _maxUnlockSchedules = 0;
uint256 private _initialSharesPerToken = 0;
struct Stake {
uint256 stakingShares;
uint256 timestampSec;
}
struct UserTotals {
uint256 stakingShares;
uint256 stakingShareSeconds;
uint256 lastAccountingTimestampSec;
}
mapping(address => UserTotals) private _userTotals;
mapping(address => Stake[]) private _userStakes;
struct UnlockSchedule {
uint256 initialLockedShares;
uint256 unlockedShares;
uint256 lastUnlockTimestampSec;
uint256 endAtSec;
uint256 durationSec;
}
UnlockSchedule[] public unlockSchedules;
constructor(IERC20 stakingToken, IERC20 distributionToken, uint256 maxUnlockSchedules,
uint256 startBonus_, uint256 bonusPeriodSec_, uint256 initialSharesPerToken) public {
require(startBonus_ <= 10**BONUS_DECIMALS, 'Sunshine Reserve: start bonus too high');
require(bonusPeriodSec_ != 0, 'Sunshine Reserve: bonus period is zero');
require(initialSharesPerToken > 0, 'Sunshine Reserve: initialSharesPerToken is zero');
_stakingPool = new TokenPool(stakingToken);
_unlockedPool = new TokenPool(distributionToken);
_lockedPool = new TokenPool(distributionToken);
startBonus = startBonus_;
bonusPeriodSec = bonusPeriodSec_;
_maxUnlockSchedules = maxUnlockSchedules;
_initialSharesPerToken = initialSharesPerToken;
}
function getStakingToken() public view returns (IERC20) {
return _stakingPool.token();
}
function getDistributionToken() public view returns (IERC20) {
assert(_unlockedPool.token() == _lockedPool.token());
return _unlockedPool.token();
}
function stake(uint256 amount, bytes calldata data) external {
_stakeFor(msg.sender, msg.sender, amount);
}
function stakeFor(address user, uint256 amount, bytes calldata data) external {
_stakeFor(msg.sender, user, amount);
}
function _stakeFor(address staker, address beneficiary, uint256 amount) private {
require(amount > 0, 'Sunshine Reserve: stake amount is zero');
require(beneficiary != address(0), 'Sunshine Reserve: beneficiary is zero address');
require(totalStakingShares == 0 || totalStaked() > 0,
'Sunshine Reserve: Invalid state. Staking shares exist, but no staking tokens do');
uint256 mintedStakingShares = (totalStakingShares > 0)
? totalStakingShares.mul(amount).div(totalStaked())
: amount.mul(_initialSharesPerToken);
require(mintedStakingShares > 0, 'Sunshine Reserve: Stake amount is too small');
updateAccounting();
UserTotals storage totals = _userTotals[beneficiary];
totals.stakingShares = totals.stakingShares.add(mintedStakingShares);
totals.lastAccountingTimestampSec = now;
Stake memory newStake = Stake(mintedStakingShares, now);
_userStakes[beneficiary].push(newStake);
totalStakingShares = totalStakingShares.add(mintedStakingShares);
require(_stakingPool.token().transferFrom(staker, address(_stakingPool), amount),
'Sunshine Reserve: transfer into staking pool failed');
emit Staked(beneficiary, amount, totalStakedFor(beneficiary), "");
}
function unstake(uint256 amount, bytes calldata data) external {
_unstake(amount);
}
function unstakeQuery(uint256 amount) public returns (uint256) {
return _unstake(amount);
}
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
require(amount > 0, 'Sunshine Reserve: unstake amount is zero');
require(totalStakedFor(msg.sender) >= amount,
'Sunshine Reserve: unstake amount is greater than total user stakes');
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked());
require(stakingSharesToBurn > 0, 'Sunshine Reserve: Unable to unstake amount this small');
UserTotals storage totals = _userTotals[msg.sender];
Stake[] storage accountStakes = _userStakes[msg.sender];
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
accountStakes.length--;
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
'Sunshine Reserve: transfer out of staking pool failed');
require(_unlockedPool.transfer(msg.sender, rewardAmount),
'Sunshine Reserve: transfer out of unlocked pool failed');
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
emit TokensClaimed(msg.sender, rewardAmount);
require(totalStakingShares == 0 || totalStaked() > 0,
"Sunshine Reserve: Error unstaking. Staking shares exist, but no staking tokens do");
return rewardAmount;
}
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
require(amount > 0, 'Sunshine Reserve: unstake amount is zero');
require(totalStakedFor(msg.sender) >= amount,
'Sunshine Reserve: unstake amount is greater than total user stakes');
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked());
require(stakingSharesToBurn > 0, 'Sunshine Reserve: Unable to unstake amount this small');
UserTotals storage totals = _userTotals[msg.sender];
Stake[] storage accountStakes = _userStakes[msg.sender];
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
accountStakes.length--;
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
'Sunshine Reserve: transfer out of staking pool failed');
require(_unlockedPool.transfer(msg.sender, rewardAmount),
'Sunshine Reserve: transfer out of unlocked pool failed');
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
emit TokensClaimed(msg.sender, rewardAmount);
require(totalStakingShares == 0 || totalStaked() > 0,
"Sunshine Reserve: Error unstaking. Staking shares exist, but no staking tokens do");
return rewardAmount;
}
function _unstake(uint256 amount) private returns (uint256) {
updateAccounting();
require(amount > 0, 'Sunshine Reserve: unstake amount is zero');
require(totalStakedFor(msg.sender) >= amount,
'Sunshine Reserve: unstake amount is greater than total user stakes');
uint256 stakingSharesToBurn = totalStakingShares.mul(amount).div(totalStaked());
require(stakingSharesToBurn > 0, 'Sunshine Reserve: Unable to unstake amount this small');
UserTotals storage totals = _userTotals[msg.sender];
Stake[] storage accountStakes = _userStakes[msg.sender];
uint256 stakingShareSecondsToBurn = 0;
uint256 sharesLeftToBurn = stakingSharesToBurn;
uint256 rewardAmount = 0;
while (sharesLeftToBurn > 0) {
Stake storage lastStake = accountStakes[accountStakes.length - 1];
uint256 stakeTimeSec = now.sub(lastStake.timestampSec);
uint256 newStakingShareSecondsToBurn = 0;
if (lastStake.stakingShares <= sharesLeftToBurn) {
newStakingShareSecondsToBurn = lastStake.stakingShares.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
sharesLeftToBurn = sharesLeftToBurn.sub(lastStake.stakingShares);
accountStakes.length--;
newStakingShareSecondsToBurn = sharesLeftToBurn.mul(stakeTimeSec);
rewardAmount = computeNewReward(rewardAmount, newStakingShareSecondsToBurn, stakeTimeSec);
stakingShareSecondsToBurn = stakingShareSecondsToBurn.add(newStakingShareSecondsToBurn);
lastStake.stakingShares = lastStake.stakingShares.sub(sharesLeftToBurn);
sharesLeftToBurn = 0;
}
}
totals.stakingShareSeconds = totals.stakingShareSeconds.sub(stakingShareSecondsToBurn);
totals.stakingShares = totals.stakingShares.sub(stakingSharesToBurn);
totalStakingShares = totalStakingShares.sub(stakingSharesToBurn);
'Sunshine Reserve: transfer out of staking pool failed');
require(_unlockedPool.transfer(msg.sender, rewardAmount),
'Sunshine Reserve: transfer out of unlocked pool failed');
emit Unstaked(msg.sender, amount, totalStakedFor(msg.sender), "");
emit TokensClaimed(msg.sender, rewardAmount);
require(totalStakingShares == 0 || totalStaked() > 0,
"Sunshine Reserve: Error unstaking. Staking shares exist, but no staking tokens do");
return rewardAmount;
}
} else {
_totalStakingShareSeconds = _totalStakingShareSeconds.sub(stakingShareSecondsToBurn);
require(_stakingPool.transfer(msg.sender, amount),
function computeNewReward(uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked()
.mul(stakingShareSeconds)
.div(_totalStakingShareSeconds);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**BONUS_DECIMALS;
uint256 bonusedReward =
startBonus
.add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec))
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
function computeNewReward(uint256 currentRewardTokens,
uint256 stakingShareSeconds,
uint256 stakeTimeSec) private view returns (uint256) {
uint256 newRewardTokens =
totalUnlocked()
.mul(stakingShareSeconds)
.div(_totalStakingShareSeconds);
if (stakeTimeSec >= bonusPeriodSec) {
return currentRewardTokens.add(newRewardTokens);
}
uint256 oneHundredPct = 10**BONUS_DECIMALS;
uint256 bonusedReward =
startBonus
.add(oneHundredPct.sub(startBonus).mul(stakeTimeSec).div(bonusPeriodSec))
.mul(newRewardTokens)
.div(oneHundredPct);
return currentRewardTokens.add(bonusedReward);
}
function totalStakedFor(address addr) public view returns (uint256) {
return totalStakingShares > 0 ?
totalStaked().mul(_userTotals[addr].stakingShares).div(totalStakingShares) : 0;
}
function totalStaked() public view returns (uint256) {
return _stakingPool.balance();
}
function token() external view returns (address) {
return address(getStakingToken());
}
function updateAccounting() public returns (
uint256, uint256, uint256, uint256, uint256, uint256) {
unlockTokens();
uint256 newStakingShareSeconds =
now
.sub(_lastAccountingTimestampSec)
.mul(totalStakingShares);
_totalStakingShareSeconds = _totalStakingShareSeconds.add(newStakingShareSeconds);
_lastAccountingTimestampSec = now;
UserTotals storage totals = _userTotals[msg.sender];
uint256 newUserStakingShareSeconds =
now
.sub(totals.lastAccountingTimestampSec)
.mul(totals.stakingShares);
totals.stakingShareSeconds =
totals.stakingShareSeconds
.add(newUserStakingShareSeconds);
totals.lastAccountingTimestampSec = now;
uint256 totalUserRewards = (_totalStakingShareSeconds > 0)
? totalUnlocked().mul(totals.stakingShareSeconds).div(_totalStakingShareSeconds)
: 0;
return (
totalLocked(),
totalUnlocked(),
totals.stakingShareSeconds,
_totalStakingShareSeconds,
totalUserRewards,
now
);
}
function totalLocked() public view returns (uint256) {
return _lockedPool.balance();
}
function totalUnlocked() public view returns (uint256) {
return _unlockedPool.balance();
}
function unlockScheduleCount() public view returns (uint256) {
return unlockSchedules.length;
}
function lockTokens(uint256 amount, uint256 durationSec) external onlyOwner {
require(unlockSchedules.length < _maxUnlockSchedules,
'Sunshine Reserve: reached maximum unlock schedules');
updateAccounting();
uint256 lockedTokens = totalLocked();
uint256 mintedLockedShares = (lockedTokens > 0)
? totalLockedShares.mul(amount).div(lockedTokens)
: amount.mul(_initialSharesPerToken);
UnlockSchedule memory schedule;
schedule.initialLockedShares = mintedLockedShares;
schedule.lastUnlockTimestampSec = now;
schedule.endAtSec = now.add(durationSec);
schedule.durationSec = durationSec;
unlockSchedules.push(schedule);
totalLockedShares = totalLockedShares.add(mintedLockedShares);
require(_lockedPool.token().transferFrom(msg.sender, address(_lockedPool), amount),
'Sunshine Reserve: transfer into locked pool failed');
emit TokensLocked(amount, durationSec, totalLocked());
}
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'Sunshine Reserve: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'Sunshine Reserve: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
} else {
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'Sunshine Reserve: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
function unlockTokens() public returns (uint256) {
uint256 unlockedTokens = 0;
uint256 lockedTokens = totalLocked();
if (totalLockedShares == 0) {
unlockedTokens = lockedTokens;
uint256 unlockedShares = 0;
for (uint256 s = 0; s < unlockSchedules.length; s++) {
unlockedShares = unlockedShares.add(unlockScheduleShares(s));
}
unlockedTokens = unlockedShares.mul(lockedTokens).div(totalLockedShares);
totalLockedShares = totalLockedShares.sub(unlockedShares);
}
if (unlockedTokens > 0) {
require(_lockedPool.transfer(address(_unlockedPool), unlockedTokens),
'Sunshine Reserve: transfer out of locked pool failed');
emit TokensUnlocked(unlockedTokens, totalLocked());
}
return unlockedTokens;
}
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if(schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
if (now >= schedule.endAtSec) {
sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));
schedule.lastUnlockTimestampSec = schedule.endAtSec;
sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if(schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
if (now >= schedule.endAtSec) {
sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));
schedule.lastUnlockTimestampSec = schedule.endAtSec;
sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
function unlockScheduleShares(uint256 s) private returns (uint256) {
UnlockSchedule storage schedule = unlockSchedules[s];
if(schedule.unlockedShares >= schedule.initialLockedShares) {
return 0;
}
uint256 sharesToUnlock = 0;
if (now >= schedule.endAtSec) {
sharesToUnlock = (schedule.initialLockedShares.sub(schedule.unlockedShares));
schedule.lastUnlockTimestampSec = schedule.endAtSec;
sharesToUnlock = now.sub(schedule.lastUnlockTimestampSec)
.mul(schedule.initialLockedShares)
.div(schedule.durationSec);
schedule.lastUnlockTimestampSec = now;
}
schedule.unlockedShares = schedule.unlockedShares.add(sharesToUnlock);
return sharesToUnlock;
}
} else {
function rescueFundsFromStakingPool(address tokenToRescue, address to, uint256 amount)
public onlyOwner returns (bool) {
return _stakingPool.rescueFunds(tokenToRescue, to, amount);
}
} | 2,065,326 | [
1,
7417,
5412,
471,
11310,
8482,
2319,
622,
27824,
3844,
30,
3967,
329,
2430,
16,
2078,
30,
10710,
8586,
2430,
2647,
17,
18688,
407,
859,
8510,
2236,
310,
919,
2177,
2236,
310,
919,
868,
6706,
87,
279,
2202,
384,
911,
364,
279,
729,
18,
432,
729,
2026,
1240,
3229,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
432,
4566,
48,
16113,
318,
674,
558,
607,
6527,
353,
467,
510,
6159,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
871,
934,
9477,
12,
2867,
8808,
729,
16,
2254,
5034,
3844,
16,
2254,
5034,
2078,
16,
1731,
501,
1769,
203,
565,
871,
1351,
334,
9477,
12,
2867,
8808,
729,
16,
2254,
5034,
3844,
16,
2254,
5034,
2078,
16,
1731,
501,
1769,
203,
565,
871,
13899,
9762,
329,
12,
2867,
8808,
729,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
13899,
8966,
12,
11890,
5034,
3844,
16,
2254,
5034,
3734,
2194,
16,
2254,
5034,
2078,
1769,
203,
565,
871,
13899,
7087,
329,
12,
11890,
5034,
3844,
16,
2254,
5034,
2078,
1769,
203,
203,
565,
3155,
2864,
3238,
389,
334,
6159,
2864,
31,
203,
565,
3155,
2864,
3238,
389,
318,
15091,
2864,
31,
203,
565,
3155,
2864,
3238,
389,
15091,
2864,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
605,
673,
3378,
67,
23816,
55,
273,
576,
31,
203,
565,
2254,
5034,
1071,
787,
38,
22889,
273,
374,
31,
203,
565,
2254,
5034,
1071,
324,
22889,
5027,
2194,
273,
374,
31,
203,
203,
565,
2254,
5034,
1071,
2078,
8966,
24051,
273,
374,
31,
203,
565,
2254,
5034,
1071,
2078,
510,
6159,
24051,
273,
374,
31,
203,
565,
2254,
5034,
3238,
389,
4963,
510,
6159,
9535,
6762,
273,
374,
31,
203,
565,
2254,
5034,
3238,
389,
2722,
3032,
310,
4921,
2194,
273,
2037,
31,
203,
565,
2254,
5034,
3238,
389,
1896,
7087,
27073,
273,
374,
31,
203,
2
] |
./full_match/80001/0x20747FA1E7758a9F8D1E36Cf91A6bf2fc05aBf5e/sources/lib/hyperlane-monorepo/solidity/contracts/libs/Message.sol | * @notice Returns the message destination domain. @param _message ABI encoded Hyperlane message. @return Destination domain of `_message`/ | function destination(bytes calldata _message)
internal
pure
returns (uint32)
{
return uint32(bytes4(_message[DESTINATION_OFFSET:RECIPIENT_OFFSET]));
}
| 845,421 | [
1,
1356,
326,
883,
2929,
2461,
18,
225,
389,
2150,
10336,
45,
3749,
18274,
29351,
883,
18,
327,
10691,
2461,
434,
1375,
67,
2150,
68,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2929,
12,
3890,
745,
892,
389,
2150,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
11890,
1578,
13,
203,
565,
288,
203,
3639,
327,
2254,
1578,
12,
3890,
24,
24899,
2150,
63,
29451,
67,
11271,
30,
862,
7266,
1102,
2222,
67,
11271,
5717,
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
] |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.0;
/**
* @title Governance
* @dev The Governance contract allows to execute certain actions via majority of votes.
*/
contract Governance {
mapping(bytes32 => Proposal) public proposals;
bytes32[] public proposalsHashes;
uint256 public proposalsCount;
mapping(address => bool) public isVoter;
address[] public voters;
uint256 public votersCount;
struct Proposal {
bool finished;
uint256 yesVotes;
uint256 noVotes;
uint256 totalVoters;
mapping(address => bool) votedFor;
mapping(address => bool) votedAgainst;
address targetContract;
bytes data;
}
event ProposalStarted(bytes32 proposalHash);
event ProposalFinished(bytes32 proposalHash);
event ProposalExecuted(bytes32 proposalHash);
event Vote(bytes32 proposalHash, bool vote, uint256 yesVotes, uint256 noVotes, uint256 votersCount);
event VoterAdded(address voter);
event VoterDeleted(address voter);
/**
* @dev The Governance constructor adds sender to voters list.
*/
constructor(address[] memory _voters) {
for (uint256 i=0; i<_voters.length; i++){
voters.push(_voters[i]);
isVoter[_voters[i]] = true;
}
proposalsCount = 0;
votersCount = _voters.length;
}
/**
* @dev Throws if called by any account other than the voter.
*/
modifier onlyVoter() {
require(isVoter[msg.sender], "Should be voter");
_;
}
/**
* @dev Throws if called by any account other than the Governance contract.
*/
modifier onlyMe() {
require(msg.sender == address(this), "Call only via Governance");
_;
}
/**
* @dev Creates a new voting proposal for the execution `_data` of `_targetContract`.
* Only voter can create a new proposal.
*
* Requirements:
*
* - `_targetContract` cannot be the zero address.
* - `_data` length must not be less than 4 bytes.
*
* @notice Create a new voting proposal for the execution `_data` of `_targetContract`. You must be voter.
* @param _targetContract Target contract address that can execute target `_data`
* @param _data Target calldata to execute
*/
function newProposal(address _targetContract, bytes memory _data) public onlyVoter {
require(_targetContract != address(0), "Address must be non-zero");
require(_data.length >= 4, "Tx must be 4+ bytes");
// solhint-disable not-rely-on-time
bytes32 _proposalHash = keccak256(abi.encodePacked(_targetContract, _data, block.timestamp));
require(proposals[_proposalHash].data.length == 0, "The poll has already been initiated");
proposals[_proposalHash].targetContract = _targetContract;
proposals[_proposalHash].data = _data;
proposals[_proposalHash].totalVoters = votersCount;
proposalsHashes.push(_proposalHash);
proposalsCount = proposalsCount + 1;
emit ProposalStarted(_proposalHash);
}
/**
* @dev Adds sender's vote to the proposal and then follows the majority voting algoritm.
*
* Requirements:
*
* - proposal with `_proposalHash` must not be finished.
* - sender must not be already voted.
*
* @notice Vote "for" or "against" in proposal with `_proposalHash` hash.
* @param _proposalHash Unique mapping key of proposal
* @param _yes 1 is vote "for" and 0 is "against"
*/
function vote(bytes32 _proposalHash, bool _yes) public onlyVoter {
// solhint-disable code-complexity
require(!proposals[_proposalHash].finished, "Already finished");
require(!proposals[_proposalHash].votedFor[msg.sender], "Already voted");
require(!proposals[_proposalHash].votedAgainst[msg.sender], "Already voted");
if (proposals[_proposalHash].totalVoters != votersCount) proposals[_proposalHash].totalVoters = votersCount;
if (_yes) {
proposals[_proposalHash].yesVotes = proposals[_proposalHash].yesVotes + 1;
proposals[_proposalHash].votedFor[msg.sender] = true;
} else {
proposals[_proposalHash].noVotes = proposals[_proposalHash].noVotes + 1;
proposals[_proposalHash].votedAgainst[msg.sender] = true;
}
emit Vote(
_proposalHash,
_yes,
proposals[_proposalHash].yesVotes,
proposals[_proposalHash].noVotes,
votersCount
);
if (proposals[_proposalHash].yesVotes > votersCount / 2) {
executeProposal(_proposalHash);
finishProposal(_proposalHash);
} else if (proposals[_proposalHash].noVotes >= (votersCount + 1) / 2) {
finishProposal(_proposalHash);
}
}
/**
* @dev Returns true in first output if `_address` is already voted in
* proposal with `_proposalHash` hash.
* Second output shows, if voter is voted for (true) or against (false).
*
* @param _proposalHash Unique mapping key of proposal
* @param _address Address of the one who is checked
*/
function getVoted(bytes32 _proposalHash, address _address) public view returns (bool, bool) {
bool isVoted = proposals[_proposalHash].votedFor[_address] || proposals[_proposalHash].votedAgainst[_address];
bool side = proposals[_proposalHash].votedFor[_address];
return (isVoted, side);
}
/**
* @dev Adds `_address` to the voters list.
* This method can be executed only via proposal of this Governance contract.
*
* Requirements:
*
* - `_address` cannot be the zero address.
* - `_address` cannot be already in voters list.
*
* @param _address Address of voter to add
*/
function addVoter(address _address) public onlyMe {
require(_address != address(0), "Need non-zero address");
require(!isVoter[_address], "Already in voters list");
voters.push(_address);
isVoter[_address] = true;
votersCount = votersCount + 1;
emit VoterAdded(_address);
}
/**
* @dev Removes `_address` from the voters list.
* This method can be executed only via proposal of this Governance contract.
*
* Requirements:
*
* - `_address` must be in voters list.
* - Num of voters must be more than one.
*
* @param _address Address of voter to delete
*/
function delVoter(address _address) public onlyMe {
require(isVoter[_address], "Not in voters list");
require(votersCount > 1, "Can not delete single voter");
for (uint256 i = 0; i < voters.length; i++) {
if (voters[i] == _address) {
if (voters.length > 1) {
voters[i] = voters[voters.length - 1];
}
voters.pop(); // Implicitly recovers gas from last element storage
isVoter[_address] = false;
votersCount = votersCount - 1;
emit VoterDeleted(_address);
break;
}
}
}
/**
* @dev Executes data in proposal with `_proposalHash` hash.
* This method can be executed only from vote() method.
*/
function executeProposal(bytes32 _proposalHash) internal {
require(!proposals[_proposalHash].finished, "Already finished");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returnData) = address(proposals[_proposalHash].targetContract).call(
proposals[_proposalHash].data
);
require(success, string(returnData));
emit ProposalExecuted(_proposalHash);
}
/**
* @dev Finishes proposal with `_proposalHash` hash.
* This method can be executed only from vote() method.
*/
function finishProposal(bytes32 _proposalHash) internal {
require(!proposals[_proposalHash].finished, "Already finished");
proposals[_proposalHash].finished = true;
emit ProposalFinished(_proposalHash);
}
} | * @dev Removes `_address` from the voters list. This method can be executed only via proposal of this Governance contract. Requirements: - `_address` must be in voters list. - Num of voters must be more than one. @param _address Address of voter to delete/ | function delVoter(address _address) public onlyMe {
require(isVoter[_address], "Not in voters list");
require(votersCount > 1, "Can not delete single voter");
for (uint256 i = 0; i < voters.length; i++) {
if (voters[i] == _address) {
if (voters.length > 1) {
voters[i] = voters[voters.length - 1];
}
isVoter[_address] = false;
votersCount = votersCount - 1;
emit VoterDeleted(_address);
break;
}
}
}
| 10,758,964 | [
1,
6220,
1375,
67,
2867,
68,
628,
326,
331,
352,
414,
666,
18,
1220,
707,
848,
506,
7120,
1338,
3970,
14708,
434,
333,
611,
1643,
82,
1359,
6835,
18,
29076,
30,
300,
1375,
67,
2867,
68,
1297,
506,
316,
331,
352,
414,
666,
18,
300,
6805,
434,
331,
352,
414,
1297,
506,
1898,
2353,
1245,
18,
225,
389,
2867,
5267,
434,
331,
20005,
358,
1430,
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
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] | [
1,
565,
445,
1464,
58,
20005,
12,
2867,
389,
2867,
13,
1071,
1338,
4667,
288,
203,
3639,
2583,
12,
291,
58,
20005,
63,
67,
2867,
6487,
315,
1248,
316,
331,
352,
414,
666,
8863,
203,
3639,
2583,
12,
90,
352,
414,
1380,
405,
404,
16,
315,
2568,
486,
1430,
2202,
331,
20005,
8863,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
331,
352,
414,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
261,
90,
352,
414,
63,
77,
65,
422,
389,
2867,
13,
288,
203,
7734,
309,
261,
90,
352,
414,
18,
2469,
405,
404,
13,
288,
203,
10792,
331,
352,
414,
63,
77,
65,
273,
331,
352,
414,
63,
90,
352,
414,
18,
2469,
300,
404,
15533,
203,
7734,
289,
203,
7734,
353,
58,
20005,
63,
67,
2867,
65,
273,
629,
31,
203,
7734,
331,
352,
414,
1380,
273,
331,
352,
414,
1380,
300,
404,
31,
203,
7734,
3626,
776,
20005,
7977,
24899,
2867,
1769,
203,
7734,
898,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC20FeeProxy
* @notice This contract performs an ERC20 token transfer, with a Fee sent to a third address and stores a reference
*/
contract ERC20FeeProxy {
// Event to declare a transfer with a reference
event TransferWithReferenceAndFee(
address tokenAddress,
address to,
uint256 amount,
bytes indexed paymentReference,
uint256 feeAmount,
address feeAddress
);
// Fallback function returns funds to the sender
receive() external payable {
revert("not payable receive");
}
/**
* @notice Performs a ERC20 token transfer with a reference
and a transfer to a second address for the payment of a fee
* @param _tokenAddress Address of the ERC20 token smart contract
* @param _to Transfer recipient
* @param _amount Amount to transfer
* @param _paymentReference Reference of the payment related
* @param _feeAmount The amount of the payment fee
* @param _feeAddress The fee recipient
*/
function transferFromWithReferenceAndFee(
address _tokenAddress,
address _to,
uint256 _amount,
bytes calldata _paymentReference,
uint256 _feeAmount,
address _feeAddress
) external
{
require(safeTransferFrom(_tokenAddress, _to, _amount), "payment transferFrom() failed");
if (_feeAmount > 0 && _feeAddress != address(0)) {
require(safeTransferFrom(_tokenAddress, _feeAddress, _feeAmount), "fee transferFrom() failed");
}
emit TransferWithReferenceAndFee(
_tokenAddress,
_to,
_amount,
_paymentReference,
_feeAmount,
_feeAddress
);
}
/**
* @notice Call transferFrom ERC20 function and validates the return data of a ERC20 contract call.
* @dev This is necessary because of non-standard ERC20 tokens that don't have a return value.
* @return result The return value of the ERC20 call, returning true for non-standard tokens
*/
function safeTransferFrom(address _tokenAddress, address _to, uint256 _amount) internal returns (bool result) {
/* solium-disable security/no-inline-assembly */
// check if the address is a contract
assembly {
if iszero(extcodesize(_tokenAddress)) { revert(0, 0) }
}
// solium-disable-next-line security/no-low-level-calls
(bool success, ) = _tokenAddress.call(abi.encodeWithSignature(
"transferFrom(address,address,uint256)",
msg.sender,
_to,
_amount
));
assembly {
switch returndatasize()
case 0 { // not a standard erc20
result := 1
}
case 32 { // standard erc20
returndatacopy(0, 0, 32)
result := mload(0)
}
default { // anything else, should revert for safety
revert(0, 0)
}
}
require(success, "transferFrom() has been reverted");
/* solium-enable security/no-inline-assembly */
return result;
}
} | * @title ERC20FeeProxy @notice This contract performs an ERC20 token transfer, with a Fee sent to a third address and stores a reference/ Event to declare a transfer with a reference Fallback function returns funds to the sender | contract ERC20FeeProxy {
event TransferWithReferenceAndFee(
address tokenAddress,
address to,
uint256 amount,
bytes indexed paymentReference,
uint256 feeAmount,
address feeAddress
);
pragma solidity ^0.8.0;
receive() external payable {
revert("not payable receive");
}
and a transfer to a second address for the payment of a fee
function transferFromWithReferenceAndFee(
address _tokenAddress,
address _to,
uint256 _amount,
bytes calldata _paymentReference,
uint256 _feeAmount,
address _feeAddress
) external
{
require(safeTransferFrom(_tokenAddress, _to, _amount), "payment transferFrom() failed");
if (_feeAmount > 0 && _feeAddress != address(0)) {
require(safeTransferFrom(_tokenAddress, _feeAddress, _feeAmount), "fee transferFrom() failed");
}
emit TransferWithReferenceAndFee(
_tokenAddress,
_to,
_amount,
_paymentReference,
_feeAmount,
_feeAddress
);
}
function transferFromWithReferenceAndFee(
address _tokenAddress,
address _to,
uint256 _amount,
bytes calldata _paymentReference,
uint256 _feeAmount,
address _feeAddress
) external
{
require(safeTransferFrom(_tokenAddress, _to, _amount), "payment transferFrom() failed");
if (_feeAmount > 0 && _feeAddress != address(0)) {
require(safeTransferFrom(_tokenAddress, _feeAddress, _feeAmount), "fee transferFrom() failed");
}
emit TransferWithReferenceAndFee(
_tokenAddress,
_to,
_amount,
_paymentReference,
_feeAmount,
_feeAddress
);
}
function safeTransferFrom(address _tokenAddress, address _to, uint256 _amount) internal returns (bool result) {
assembly {
}
"transferFrom(address,address,uint256)",
msg.sender,
_to,
_amount
));
assembly {
switch returndatasize()
result := 1
}
returndatacopy(0, 0, 32)
result := mload(0)
}
revert(0, 0)
function safeTransferFrom(address _tokenAddress, address _to, uint256 _amount) internal returns (bool result) {
assembly {
}
"transferFrom(address,address,uint256)",
msg.sender,
_to,
_amount
));
assembly {
switch returndatasize()
result := 1
}
returndatacopy(0, 0, 32)
result := mload(0)
}
revert(0, 0)
if iszero(extcodesize(_tokenAddress)) { revert(0, 0) }
(bool success, ) = _tokenAddress.call(abi.encodeWithSignature(
function safeTransferFrom(address _tokenAddress, address _to, uint256 _amount) internal returns (bool result) {
assembly {
}
"transferFrom(address,address,uint256)",
msg.sender,
_to,
_amount
));
assembly {
switch returndatasize()
result := 1
}
returndatacopy(0, 0, 32)
result := mload(0)
}
revert(0, 0)
}
| 7,870,975 | [
1,
654,
39,
3462,
14667,
3886,
225,
1220,
6835,
11199,
392,
4232,
39,
3462,
1147,
7412,
16,
598,
279,
30174,
3271,
358,
279,
12126,
1758,
471,
9064,
279,
2114,
19,
2587,
358,
14196,
279,
7412,
598,
279,
2114,
21725,
445,
1135,
284,
19156,
358,
326,
5793,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
4232,
39,
3462,
14667,
3886,
288,
203,
225,
871,
12279,
1190,
2404,
1876,
14667,
12,
203,
565,
1758,
1147,
1887,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
3844,
16,
203,
565,
1731,
8808,
5184,
2404,
16,
203,
565,
2254,
5034,
14036,
6275,
16,
203,
565,
1758,
14036,
1887,
203,
225,
11272,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
225,
6798,
1435,
3903,
8843,
429,
288,
203,
565,
15226,
2932,
902,
8843,
429,
6798,
8863,
203,
225,
289,
203,
203,
2868,
471,
279,
7412,
358,
279,
2205,
1758,
364,
326,
5184,
434,
279,
14036,
203,
225,
445,
7412,
1265,
1190,
2404,
1876,
14667,
12,
203,
565,
1758,
389,
2316,
1887,
16,
203,
565,
1758,
389,
869,
16,
203,
565,
2254,
5034,
389,
8949,
16,
203,
565,
1731,
745,
892,
389,
9261,
2404,
16,
203,
565,
2254,
5034,
389,
21386,
6275,
16,
203,
565,
1758,
389,
21386,
1887,
203,
565,
262,
3903,
203,
565,
288,
203,
565,
2583,
12,
4626,
5912,
1265,
24899,
2316,
1887,
16,
389,
869,
16,
389,
8949,
3631,
315,
9261,
7412,
1265,
1435,
2535,
8863,
203,
565,
309,
261,
67,
21386,
6275,
405,
374,
597,
389,
21386,
1887,
480,
1758,
12,
20,
3719,
288,
203,
1377,
2583,
12,
4626,
5912,
1265,
24899,
2316,
1887,
16,
389,
21386,
1887,
16,
389,
21386,
6275,
3631,
315,
21386,
7412,
1265,
1435,
2535,
8863,
203,
565,
289,
203,
565,
3626,
12279,
1190,
2404,
1876,
14667,
12,
203,
1377,
389,
2316,
1887,
16,
203,
1377,
389,
2
] |
// Dependency file: @openzeppelin/contracts/GSN/Context.sol
// pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Dependency file: contracts/interfaces/IKULAPDex.sol
// pragma solidity 0.5.17;
// import "../helper/ERC20Interface.sol";
// import "./IKULAPTradingProxy.sol";
interface IKULAPDex {
// /**
// * @dev when new trade occure (and success), this event will be boardcast.
// * @param _src Source token
// * @param _srcAmount amount of source tokens
// * @param _dest Destination token
// * @return _destAmount: amount of actual destination tokens
// */
// event Trade(ERC20 _src, uint256 _srcAmount, ERC20 _dest, uint256 _destAmount);
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between src and dest token by tradingProxyIndex
* Ex1: trade 0.5 ETH -> EOS
* 0, "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "500000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "21003850000000000000"
* Ex2: trade 30 EOS -> ETH
* 0, "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "30000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "740825000000000000"
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param srcAmount amount of source tokens
* @param dest Destination token
* @param minDestAmount minimun destination amount
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function trade(
uint256 tradingProxyIndex,
ERC20 src,
uint256 srcAmount,
ERC20 dest,
uint256 minDestAmount,
uint256 partnerIndex
)
external
payable
returns(uint256);
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade with multiple routes ex. UNI -> ETH -> DAI
* Ex: trade 50 UNI -> ETH -> DAI
* Step1: trade 50 UNI -> ETH
* Step2: trade xx ETH -> DAI
* srcAmount: 50 * 1e18
* routes: [0, 1]
* srcTokens: [0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984, 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE]
* destTokens: [0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, 0x6B175474E89094C44Da98b954EedeAC495271d0F]
* @param srcAmount amount of source tokens
* @param minDestAmount minimun destination amount
* @param routes Trading paths
* @param srcTokens all source of token pairs
* @param destTokens all destination of token pairs
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function tradeRoutes(
uint256 srcAmount,
uint256 minDestAmount,
uint256[] calldata routes,
ERC20[] calldata srcTokens,
ERC20[] calldata destTokens,
uint256 partnerIndex
)
external
payable
returns(uint256);
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade with split volumes to multiple-routes ex. UNI -> ETH (5%, 15% and 80%)
* @param routes Trading paths
* @param src Source token
* @param srcAmounts amount of source tokens
* @param dest Destination token
* @param minDestAmount minimun destination amount
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function splitTrades(
uint256[] calldata routes,
ERC20 src,
uint256[] calldata srcAmounts,
ERC20 dest,
uint256 minDestAmount,
uint256 partnerIndex
)
external
payable
returns(uint256);
/**
* @notice use token address 0xeee...eee for ether
* @dev get amount of destination token for given source token amount
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param dest Destination token
* @param srcAmount amount of source tokens
* @return amount of actual destination tokens
*/
function getDestinationReturnAmount(
uint256 tradingProxyIndex,
ERC20 src,
ERC20 dest,
uint256 srcAmount,
uint256 partnerIndex
)
external
view
returns(uint256);
function getDestinationReturnAmountForSplitTrades(
uint256[] calldata routes,
ERC20 src,
uint256[] calldata srcAmounts,
ERC20 dest,
uint256 partnerIndex
)
external
view
returns(uint256);
function getDestinationReturnAmountForTradeRoutes(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address[] calldata _tradingPaths,
uint256 partnerIndex
)
external
view
returns(uint256);
}
// Dependency file: contracts/interfaces/IKULAPTradingProxy.sol
// pragma solidity 0.5.17;
// import "../helper/ERC20Interface.sol";
/**
* @title KULAP Trading Proxy
* @dev The KULAP trading proxy interface has an standard functions and event
* for other smart contract to implement to join KULAP Dex as Market Maker.
*/
interface IKULAPTradingProxy {
/**
* @dev when new trade occure (and success), this event will be boardcast.
* @param _src Source token
* @param _srcAmount amount of source tokens
* @param _dest Destination token
* @return _destAmount: amount of actual destination tokens
*/
event Trade(ERC20 _src, uint256 _srcAmount, ERC20 _dest, uint256 _destAmount);
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between src and dest token
* @param _src Source token
* @param _dest Destination token
* @param _srcAmount amount of source tokens
* @return _destAmount: amount of actual destination tokens
*/
function trade(
ERC20 _src,
ERC20 _dest,
uint256 _srcAmount
)
external
payable
returns(uint256 _destAmount);
/**
* @dev provide destinationm token amount for given source amount
* @param _src Source token
* @param _dest Destination token
* @param _srcAmount Amount of source tokens
* @return _destAmount: amount of expected destination tokens
*/
function getDestinationReturnAmount(
ERC20 _src,
ERC20 _dest,
uint256 _srcAmount
)
external
view
returns(uint256 _destAmount);
/**
* @dev provide source token amount for given destination amount
* @param _src Source token
* @param _dest Destination token
* @param _destAmount Amount of destination tokens
* @return _srcAmount: amount of expected source tokens
*/
// function getSourceReturnAmount(
// ERC20 _src,
// ERC20 _dest,
// uint256 _destAmount
// )
// external
// view
// returns(uint256 _srcAmount);
}
// Dependency file: contracts/helper/ERC20Interface.sol
// pragma solidity 0.5.17;
/**
* @title ERC20
* @dev The ERC20 interface has an standard functions and event
* for erc20 compatible token on Ethereum blockchain.
*/
interface ERC20 {
function totalSupply() external view returns (uint supply);
function balanceOf(address _owner) external view returns (uint balance);
function transfer(address _to, uint _value) external; // Some ERC20 doesn't have return
function transferFrom(address _from, address _to, uint _value) external; // Some ERC20 doesn't have return
function approve(address _spender, uint _value) external; // Some ERC20 doesn't have return
function allowance(address _owner, address _spender) external view returns (uint remaining);
function decimals() external view returns(uint digits);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
// Dependency file: @openzeppelin/contracts/ownership/Ownable.sol
// pragma solidity ^0.5.0;
// import "../GSN/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.
*
* 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(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _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 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 onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Dependency 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;
}
}
// Dependency file: @openzeppelin/contracts/utils/ReentrancyGuard.sol
// pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be 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].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial 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 percetange 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.
_notEntered = true;
}
/**
* @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(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity 0.5.17;
// import '@openzeppelin/contracts/utils/ReentrancyGuard.sol';
// import "@openzeppelin/contracts/math/SafeMath.sol";
// import "@openzeppelin/contracts/ownership/Ownable.sol";
// import "./helper/ERC20Interface.sol";
// import "./interfaces/IKULAPTradingProxy.sol";
// import "./interfaces/IKULAPDex.sol";
contract ProxyManagement is Ownable {
/**
* @dev Struct of trading proxy
* @param name Name of trading proxy.
* @param enable The flag of trading proxy to check is trading proxy enable.
* @param proxy The address of trading proxy.
*/
struct Proxy {
string name;
bool enable;
IKULAPTradingProxy proxy;
}
event AddedTradingProxy(
address indexed addedBy,
string name,
IKULAPTradingProxy indexed proxyAddress,
uint256 indexed index
);
event EnabledTradingProxy(
address indexed enabledBy,
string name,
IKULAPTradingProxy proxyAddress,
uint256 indexed index
);
event DisabledTradingProxy(
address indexed disabledBy,
string name,
IKULAPTradingProxy indexed proxyAddress,
uint256 indexed index
);
Proxy[] public tradingProxies; // list of trading proxies
modifier onlyTradingProxyEnabled(uint _index) {
require(tradingProxies[_index].enable == true, "This trading proxy is disabled");
_;
}
modifier onlyTradingProxyDisabled(uint _index) {
require(tradingProxies[_index].enable == false, "This trading proxy is enabled");
_;
}
/**
* @dev Function for adding new trading proxy
* @param _name Name of trading proxy.
* @param _proxyAddress The address of trading proxy.
* @return length of trading proxies.
*/
function addTradingProxy(
string memory _name,
IKULAPTradingProxy _proxyAddress
)
public
onlyOwner
{
tradingProxies.push(Proxy({
name: _name,
enable: true,
proxy: _proxyAddress
}));
emit AddedTradingProxy(msg.sender, _name, _proxyAddress, tradingProxies.length - 1);
}
/**
* @dev Function for disable trading proxy by index
* @param _index The uint256 of trading proxy index.
* @return length of trading proxies.
*/
function disableTradingProxy(
uint256 _index
)
public
onlyOwner
onlyTradingProxyEnabled(_index)
{
tradingProxies[_index].enable = false;
emit DisabledTradingProxy(msg.sender, tradingProxies[_index].name, tradingProxies[_index].proxy, _index);
}
/**
* @dev Function for enale trading proxy by index
* @param _index The uint256 of trading proxy index.
* @return length of trading proxies.
*/
function enableTradingProxy(
uint256 _index
)
public
onlyOwner
onlyTradingProxyDisabled(_index)
{
tradingProxies[_index].enable = true;
emit EnabledTradingProxy(msg.sender, tradingProxies[_index].name, tradingProxies[_index].proxy, _index);
}
/**
* @dev Function for get amount of trading proxy
* @return Amount of trading proxies.
*/
function getProxyCount() public view returns (uint256) {
return tradingProxies.length;
}
/**
* @dev Function for get enable status of trading proxy
* @param _index The uint256 of trading proxy index.
* @return enable status of trading proxy.
*/
function isTradingProxyEnable(uint256 _index) public view returns (bool) {
return tradingProxies[_index].enable;
}
}
/*
* Fee collection by partner reference
*/
contract Partnership is ProxyManagement {
using SafeMath for uint256;
struct Partner {
address wallet; // To receive fee on the KULAP Dex network
uint16 fee; // fee in bps
bytes16 name; // Partner reference
}
mapping(uint256 => Partner) public partners;
constructor() public {
Partner memory partner = Partner(msg.sender, 0, "KULAP");
partners[0] = partner;
}
function updatePartner(uint256 index, address wallet, uint16 fee, bytes16 name)
external
onlyOwner
{
Partner memory partner = Partner(wallet, fee, name);
partners[index] = partner;
}
function amountWithFee(uint256 amount, uint256 partnerIndex)
internal
view
returns(uint256 remainingAmount)
{
Partner storage partner = partners[partnerIndex];
if (partner.fee == 0) {
return amount;
}
uint256 fee = amount.mul(partner.fee).div(10000);
return amount.sub(fee);
}
function collectFee(uint256 partnerIndex, uint256 amount, ERC20 token)
internal
returns(uint256 remainingAmount)
{
Partner storage partner = partners[partnerIndex];
if (partner.fee == 0) {
return amount;
}
uint256 fee = amount.mul(partner.fee).div(10000);
require(fee < amount, "fee exceeds return amount!");
token.transfer(partner.wallet, fee);
return amount.sub(fee);
}
}
contract KULAPDex is IKULAPDex, Partnership, ReentrancyGuard {
event Trade(
address indexed srcAsset, // Source
uint256 srcAmount,
address indexed destAsset, // Destination
uint256 destAmount,
address indexed trader, // User
uint256 fee // System fee
);
using SafeMath for uint256;
ERC20 public etherERC20 = ERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between Ether to token by tradingProxyIndex
* @param tradingProxyIndex index of trading proxy
* @param srcAmount amount of source tokens
* @param dest Destination token
* @return amount of actual destination tokens
*/
function _tradeEtherToToken(
uint256 tradingProxyIndex,
uint256 srcAmount,
ERC20 dest
)
private
returns(uint256)
{
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
// Trade to proxy
uint256 destAmount = tradingProxy.trade.value(srcAmount)(
etherERC20,
dest,
srcAmount
);
return destAmount;
}
// Receive ETH in case of trade Token -> ETH, will get ETH back from trading proxy
function () external payable {}
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between token to Ether by tradingProxyIndex
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param srcAmount amount of source tokens
* @return amount of actual destination tokens
*/
function _tradeTokenToEther(
uint256 tradingProxyIndex,
ERC20 src,
uint256 srcAmount
)
private
returns(uint256)
{
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
// Approve to TradingProxy
src.approve(address(tradingProxy), srcAmount);
// Trande to proxy
uint256 destAmount = tradingProxy.trade(
src,
etherERC20,
srcAmount
);
return destAmount;
}
/**
* @dev makes a trade between token to token by tradingProxyIndex
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param srcAmount amount of source tokens
* @param dest Destination token
* @return amount of actual destination tokens
*/
function _tradeTokenToToken(
uint256 tradingProxyIndex,
ERC20 src,
uint256 srcAmount,
ERC20 dest
)
private
returns(uint256)
{
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
// Approve to TradingProxy
src.approve(address(tradingProxy), srcAmount);
// Trande to proxy
uint256 destAmount = tradingProxy.trade(
src,
dest,
srcAmount
);
return destAmount;
}
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between src and dest token by tradingProxyIndex
* Ex1: trade 0.5 ETH -> DAI
* 0, "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "500000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "21003850000000000000"
* Ex2: trade 30 DAI -> ETH
* 0, "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "30000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "740825000000000000"
* @param _tradingProxyIndex index of trading proxy
* @param _src Source token
* @param _srcAmount amount of source tokens
* @param _dest Destination token
* @return amount of actual destination tokens
*/
function _trade(
uint256 _tradingProxyIndex,
ERC20 _src,
uint256 _srcAmount,
ERC20 _dest
)
private
onlyTradingProxyEnabled(_tradingProxyIndex)
returns(uint256)
{
// Destination amount
uint256 destAmount;
// Record src/dest asset for later consistency check.
uint256 srcAmountBefore;
uint256 destAmountBefore;
if (etherERC20 == _src) { // Source
srcAmountBefore = address(this).balance;
} else {
srcAmountBefore = _src.balanceOf(address(this));
}
if (etherERC20 == _dest) { // Dest
destAmountBefore = address(this).balance;
} else {
destAmountBefore = _dest.balanceOf(address(this));
}
if (etherERC20 == _src) { // Trade ETH -> Token
destAmount = _tradeEtherToToken(_tradingProxyIndex, _srcAmount, _dest);
} else if (etherERC20 == _dest) { // Trade Token -> ETH
destAmount = _tradeTokenToEther(_tradingProxyIndex, _src, _srcAmount);
} else { // Trade Token -> Token
destAmount = _tradeTokenToToken(_tradingProxyIndex, _src, _srcAmount, _dest);
}
// Recheck if src/dest amount correct
if (etherERC20 == _src) { // Source
require(address(this).balance == srcAmountBefore.sub(_srcAmount), "source amount mismatch after trade");
} else {
require(_src.balanceOf(address(this)) == srcAmountBefore.sub(_srcAmount), "source amount mismatch after trade");
}
if (etherERC20 == _dest) { // Dest
require(address(this).balance == destAmountBefore.add(destAmount), "destination amount mismatch after trade");
} else {
require(_dest.balanceOf(address(this)) == destAmountBefore.add(destAmount), "destination amount mismatch after trade");
}
return destAmount;
}
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade between src and dest token by tradingProxyIndex
* Ex1: trade 0.5 ETH -> DAI
* 0, "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "500000000000000000", "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "21003850000000000000"
* Ex2: trade 30 DAI -> ETH
* 0, "0xd3c64BbA75859Eb808ACE6F2A6048ecdb2d70817", "30000000000000000000", "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", "740825000000000000"
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param srcAmount amount of source tokens
* @param dest Destination token
* @param minDestAmount minimun destination amount
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function trade(
uint256 tradingProxyIndex,
ERC20 src,
uint256 srcAmount,
ERC20 dest,
uint256 minDestAmount,
uint256 partnerIndex
)
external
payable
nonReentrant
returns(uint256)
{
uint256 destAmount;
// Prepare source's asset
if (etherERC20 != src) {
src.transferFrom(msg.sender, address(this), srcAmount); // Transfer token to this address
}
// Trade with proxy
destAmount = _trade(tradingProxyIndex, src, srcAmount, dest);
// Throw exception if destination amount doesn't meet user requirement.
require(destAmount >= minDestAmount, "destination amount is too low.");
if (etherERC20 == dest) {
(bool success, ) = msg.sender.call.value(destAmount)(""); // Send back ether to sender
require(success, "Transfer ether back to caller failed.");
} else { // Send back token to sender
// Some ERC20 Smart contract not return Bool, so we can't use require(dest.transfer(x, y)); here
dest.transfer(msg.sender, destAmount);
}
// Collect fee
uint256 remainingAmount = collectFee(partnerIndex, destAmount, dest);
emit Trade(address(src), srcAmount, address(dest), remainingAmount, msg.sender, 0);
return remainingAmount;
}
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade with multiple routes ex. UNI -> ETH -> DAI
* Ex: trade 50 UNI -> ETH -> DAI
* Step1: trade 50 UNI -> ETH
* Step2: trade xx ETH -> DAI
* srcAmount: 50 * 1e18
* routes: [0, 1]
* srcTokens: [0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984, 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE]
* destTokens: [0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE, 0x6B175474E89094C44Da98b954EedeAC495271d0F]
* @param srcAmount amount of source tokens
* @param minDestAmount minimun destination amount
* @param routes Trading paths
* @param srcTokens all source of token pairs
* @param destTokens all destination of token pairs
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function tradeRoutes(
uint256 srcAmount,
uint256 minDestAmount,
uint256[] calldata routes,
ERC20[] calldata srcTokens,
ERC20[] calldata destTokens,
uint256 partnerIndex
)
external
payable
nonReentrant
returns(uint256)
{
require(routes.length > 0, "routes can not be empty");
require(routes.length == srcTokens.length && routes.length == destTokens.length, "Parameter value lengths mismatch");
uint256 remainingAmount;
{
uint256 destAmount;
if (etherERC20 != srcTokens[0]) {
srcTokens[0].transferFrom(msg.sender, address(this), srcAmount); // Transfer token to This address
}
uint256 pathSrcAmount = srcAmount;
for (uint i = 0; i < routes.length; i++) {
uint256 tradingProxyIndex = routes[i];
ERC20 pathSrc = srcTokens[i];
ERC20 pathDest = destTokens[i];
destAmount = _trade(tradingProxyIndex, pathSrc, pathSrcAmount, pathDest);
pathSrcAmount = destAmount;
}
// Throw exception if destination amount doesn't meet user requirement.
require(destAmount >= minDestAmount, "destination amount is too low.");
if (etherERC20 == destTokens[destTokens.length - 1]) { // Trade Any -> ETH
// Send back ether to sender
(bool success,) = msg.sender.call.value(destAmount)("");
require(success, "Transfer ether back to caller failed.");
} else { // Trade Any -> Token
// Send back token to sender
// Some ERC20 Smart contract not return Bool, so we can't use require(dest.transfer(x, y)) here
destTokens[destTokens.length - 1].transfer(msg.sender, destAmount);
}
// Collect fee
remainingAmount = collectFee(partnerIndex, destAmount, destTokens[destTokens.length - 1]);
}
emit Trade(address(srcTokens[0]), srcAmount, address(destTokens[destTokens.length - 1]), remainingAmount, msg.sender, 0);
return remainingAmount;
}
/**
* @notice use token address 0xeee...eee for ether
* @dev makes a trade with split volumes to multiple-routes ex. UNI -> ETH (5%, 15% and 80%)
* @param routes Trading paths
* @param src Source token
* @param srcAmounts amount of source tokens
* @param dest Destination token
* @param minDestAmount minimun destination amount
* @param partnerIndex index of partnership for revenue sharing
* @return amount of actual destination tokens
*/
function splitTrades(
uint256[] calldata routes,
ERC20 src,
uint256[] calldata srcAmounts,
ERC20 dest,
uint256 minDestAmount,
uint256 partnerIndex
)
external
payable
nonReentrant
returns(uint256)
{
require(routes.length > 0, "routes can not be empty");
require(routes.length == srcAmounts.length, "routes and srcAmounts lengths mismatch");
uint256 srcAmount = srcAmounts[0];
uint256 destAmount = 0;
// Prepare source's asset
if (etherERC20 != src) {
src.transferFrom(msg.sender, address(this), srcAmount); // Transfer token to this address
}
// Trade with proxies
for (uint i = 0; i < routes.length; i++) {
uint256 tradingProxyIndex = routes[i];
uint256 amount = srcAmounts[i];
destAmount = destAmount.add(_trade(tradingProxyIndex, src, amount, dest));
}
// Throw exception if destination amount doesn't meet user requirement.
require(destAmount >= minDestAmount, "destination amount is too low.");
if (etherERC20 == dest) {
(bool success, ) = msg.sender.call.value(destAmount)(""); // Send back ether to sender
require(success, "Transfer ether back to caller failed.");
} else { // Send back token to sender
// Some ERC20 Smart contract not return Bool, so we can't use require(dest.transfer(x, y)); here
dest.transfer(msg.sender, destAmount);
}
// Collect fee
uint256 remainingAmount = collectFee(partnerIndex, destAmount, dest);
emit Trade(address(src), srcAmount, address(dest), remainingAmount, msg.sender, 0);
return remainingAmount;
}
/**
* @notice use token address 0xeee...eee for ether
* @dev get amount of destination token for given source token amount
* @param tradingProxyIndex index of trading proxy
* @param src Source token
* @param dest Destination token
* @param srcAmount amount of source tokens
* @return amount of actual destination tokens
*/
function getDestinationReturnAmount(
uint256 tradingProxyIndex,
ERC20 src,
ERC20 dest,
uint256 srcAmount,
uint256 partnerIndex
)
external
view
returns(uint256)
{
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
uint256 destAmount = tradingProxy.getDestinationReturnAmount(src, dest, srcAmount);
return amountWithFee(destAmount, partnerIndex);
}
function getDestinationReturnAmountForSplitTrades(
uint256[] calldata routes,
ERC20 src,
uint256[] calldata srcAmounts,
ERC20 dest,
uint256 partnerIndex
)
external
view
returns(uint256)
{
require(routes.length > 0, "routes can not be empty");
require(routes.length == srcAmounts.length, "routes and srcAmounts lengths mismatch");
uint256 destAmount = 0;
for (uint i = 0; i < routes.length; i++) {
uint256 tradingProxyIndex = routes[i];
uint256 amount = srcAmounts[i];
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
destAmount = destAmount.add(tradingProxy.getDestinationReturnAmount(src, dest, amount));
}
return amountWithFee(destAmount, partnerIndex);
}
function getDestinationReturnAmountForTradeRoutes(
ERC20 src,
uint256 srcAmount,
ERC20 dest,
address[] calldata _tradingPaths,
uint256 partnerIndex
)
external
view
returns(uint256)
{
src;
dest;
uint256 destAmount;
uint256 pathSrcAmount = srcAmount;
for (uint i = 0; i < _tradingPaths.length; i += 3) {
uint256 tradingProxyIndex = uint256(_tradingPaths[i]);
ERC20 pathSrc = ERC20(_tradingPaths[i+1]);
ERC20 pathDest = ERC20(_tradingPaths[i+2]);
// Load trading proxy
IKULAPTradingProxy tradingProxy = tradingProxies[tradingProxyIndex].proxy;
destAmount = tradingProxy.getDestinationReturnAmount(pathSrc, pathDest, pathSrcAmount);
pathSrcAmount = destAmount;
}
return amountWithFee(destAmount, partnerIndex);
}
// In case of expected and unexpected event that have some token amounts remain in this contract, owner can call to collect them.
function collectRemainingToken(
ERC20 token,
uint256 amount
)
public
onlyOwner
{
token.transfer(msg.sender, amount);
}
// In case of expected and unexpected event that have some ether amounts remain in this contract, owner can call to collect them.
function collectRemainingEther(
uint256 amount
)
public
onlyOwner
{
(bool success, ) = msg.sender.call.value(amount)(""); // Send back ether to sender
require(success, "Transfer ether back to caller failed.");
}
} | Send back ether to sender | (bool success,) = msg.sender.call.value(destAmount)("");
| 10,518,669 | [
1,
3826,
1473,
225,
2437,
358,
5793,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
2868,
261,
6430,
2216,
16,
13,
273,
1234,
18,
15330,
18,
1991,
18,
1132,
12,
10488,
6275,
13,
2932,
8863,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../common/Upgradeable.sol";
contract Bridge is Upgradeable {
using SignatureUtils for TransferData;
constructor(address _proxy) Upgradeable(_proxy) {}
/**
* @dev To approve or revoke a token from acceptance list
* @param _tokenAddress the token address
* @param _value true/false
*/
function setTokenApproval(address _tokenAddress, bool _value)
public
onlyOwner
{
isApprovedToken[_tokenAddress] = _value;
}
/**
* @dev To approve or revoke a signer from list
* @param _newSigner the address of new signer
*/
function setSigner(address _newSigner) public onlyOwner {
require(_newSigner != address(0), "Bridge: signer is zero address");
require(
_newSigner != signer,
"Bridge: cannot transfer to current signer"
);
signer = _newSigner;
emit SetSignerEvent(_newSigner);
}
/**
* @dev To add or remove an account from blacklist
* @param _account the address of account
* @param _value true/false
*/
function setBlacklist(address _account, bool _value) public onlyOwner {
require(_account != address(0), "Bridge: receive zero address");
blacklist[_account] = _value;
}
/**
* @dev To check an account blacklisted or not
* @param _account the account to check
*/
function isBlacklisted(address _account) public view returns (bool) {
return blacklist[_account];
}
/**
* @dev Call when the user swap from chain A to chain B
* @notice The user will burn the token, then it will return the other token on other chain
* @param _addr (0) fromToken, (1) toToken, (2) fromAddress, (3) toAddress
* @param _data (0) amount
* @param _internalTxId the transaction id
*/
function burnToken(
address[] memory _addr,
uint256[] memory _data,
string memory _internalTxId
) public notBlacklisted nonReentrant {
TransferData memory transferData = TransferData(
_addr[0],
_addr[1],
_addr[2],
_addr[3],
_data[0],
_internalTxId
);
_execute(transferData, 0, "", address(0));
}
/**
* @dev Call when the user claim on chain B when swapping from chain A to chain B
* @param _addr (0) fromToken, (1) toToken, (2) fromAddress, (3) toAddress, (4) signer
* @param _data (0) amount
* @param _internalTxId the transaction id
* @param _signature the transaction's signature created by the signer
*/
function mintToken(
address[] memory _addr,
uint256[] memory _data,
string memory _internalTxId,
bytes memory _signature
) public notBlacklisted nonReentrant {
TransferData memory transferData = TransferData(
_addr[0],
_addr[1],
_addr[2],
_addr[3],
_data[0],
_internalTxId
);
_execute(transferData, 1, _signature, _addr[4]);
}
/**
* @dev Internal function to execute the lock/unlock request
* @param _transferData the transfer data
* @param _type 0: lock , 1: unlock
* @param _signature the transaction's signature created by the signer
*/
function _execute(
TransferData memory _transferData,
uint8 _type,
bytes memory _signature,
address _signer
) internal {
{
require(
_transferData.amount > 0,
"Diamond Alpha Bridge: Amount must be greater than 0"
);
require(
_transferData.toAddress != address(0),
"Diamond Alpha Bridge: To address is zero address"
);
require(
_transferData.fromAddress != address(0),
"Diamond Alpha Bridge: From address is zero address"
);
require(
_transferData.fromToken != address(0),
"Diamond Alpha Bridge: Token address is zero address"
);
require(
_transferData.toToken != address(0),
"Diamond Alpha Bridge: Token address is zero address"
);
}
if (_type == 0) {
// 0: Lock --> Burn, 1: Unlock --> Mint
require(
msg.sender == _transferData.fromAddress,
"Diamond Alpha Bridge: Cannot lock token"
);
require(
isApprovedToken[_transferData.fromToken],
"Diamond Alpha Bridge: Token is not supported"
);
IERC20(_transferData.fromToken).burnFrom(
_transferData.fromAddress,
_transferData.amount
);
} else {
require(
_transferData.toAddress == msg.sender,
"Diamond Alpha Bridge: You are not recipient"
);
require(_signer == signer, "Diamond Alpha Bridge: Only signer");
require(
isApprovedToken[_transferData.toToken],
"Diamond Alpha Bridge: Token is not supported"
);
require(
_transferData.verify(_signature, _signer),
"Diamond Alpha Bridge: Verify transfer data failed"
);
require(
!isExecutedTransaction[_signature],
"Diamond Alpha Bridge: Transfer data has been processed before"
);
IERC20(_transferData.toToken).mint(
_transferData.toAddress,
_transferData.amount
);
isExecutedTransaction[_signature] = true;
}
emit MintOrBurnEvent(
_transferData.internalTxId,
_transferData.toAddress,
_transferData.fromAddress,
_transferData.fromToken,
_transferData.toToken,
_transferData.amount,
_type
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ReentrancyGuard.sol";
import "../utils/SignatureUtils.sol";
import "./Structs.sol";
import "../interfaces/IERC20.sol";
import "../interfaces/IProxy.sol";
contract Upgradeable is ReentrancyGuard {
address public immutable proxy;
address public signer;
mapping(address => bool) public isApprovedToken;
mapping(bytes => bool) public isExecutedTransaction;
mapping(address => bool) blacklist;
constructor(address _proxy) {
proxy = _proxy;
}
modifier onlyOwner() {
require(
msg.sender == IProxy(proxy).proxyOwner(),
"Diamond Alpha Bridge: Only owner"
);
_;
}
modifier notBlacklisted() {
require(
!blacklist[msg.sender],
"Diamond Alpha Bridge: This address is blacklisted"
);
_;
}
event MintOrBurnEvent(
string internalTxId,
address indexed toAddress,
address indexed fromAddress,
address indexed fromToken,
address toToken,
uint256 amount,
uint8 eventType
);
event SetSignerEvent(address indexed newSigner);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../common/Structs.sol";
library SignatureUtils {
/**
* @dev To hash the transfer data into bytes32
* @param _data the transfer data
* @return hash the hash of transfer data
*/
function getMessageHash(TransferData memory _data)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
_data.fromToken,
_data.toToken,
_data.fromAddress,
_data.toAddress,
_data.amount,
_data.internalTxId
)
);
}
/**
* @dev To get the eth-signed message of hash
* @param _messageHash the hash of transfer data
* @return ethSignedMessage the eth signed message hash
*/
function getEthSignedMessageHash(bytes32 _messageHash)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
_messageHash
)
);
}
/**
* @dev To verify the transfer data and transfer signature
* @param _data the transfer data
* @param _signature the signature of transfer
* @return result true/false
*/
function verify(TransferData memory _data, bytes memory _signature, address _signer)
internal
pure
returns (bool)
{
bytes32 messageHash = getMessageHash(_data);
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return recoverSigner(ethSignedMessageHash, _signature) == _signer;
}
/**
* @dev To recover the signer from signature and hash
* @param _hash the hash of transfer data
* @param _signature the signature which was signed by the admin
* @return signer the address of signer
*/
function recoverSigner(bytes32 _hash, bytes memory _signature)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (_signature.length != 65) {
return (address(0));
}
assembly {
r := mload(add(_signature, 0x20))
s := mload(add(_signature, 0x40))
v := byte(0, mload(add(_signature, 0x60)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(_hash, v, r, s);
}
}
}
// ["0xeDb21A5bAdc10a5233767e6019C1a92AE6D14793", "0x577f0d8EE0e2C570fbC4f1f98beB85A848ef7556", "0xa781bc9ef3dc0d1e13f973264ff49531a1c84577", "0xa781bc9ef3dc0d1e13f973264ff49531a1c84577", 100000000, "62329a1cabac1e4302f4a07f"]
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct TransferData {
address fromToken;
address toToken;
address fromAddress;
address toAddress;
uint256 amount;
string internalTxId;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IERC20 {
/**
* @dev Create `amount` tokens and assigns them to `account``, increasing the total supply
*/
function mint(address account, uint256 amount) external;
/**
* @dev Destroys `amount` tokens from `account`, reducing the total supply
*/
function burnFrom(address account, uint256 amount) external;
/**
* @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;
interface IProxy {
function proxyOwner() external view returns (address);
} | * @dev To approve or revoke a signer from list @param _newSigner the address of new signer/ | function setSigner(address _newSigner) public onlyOwner {
require(_newSigner != address(0), "Bridge: signer is zero address");
require(
_newSigner != signer,
"Bridge: cannot transfer to current signer"
);
signer = _newSigner;
emit SetSignerEvent(_newSigner);
}
| 6,181,776 | [
1,
774,
6617,
537,
578,
18007,
279,
10363,
628,
666,
225,
389,
2704,
15647,
326,
1758,
434,
394,
10363,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
15647,
12,
2867,
389,
2704,
15647,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
24899,
2704,
15647,
480,
1758,
12,
20,
3631,
315,
13691,
30,
10363,
353,
3634,
1758,
8863,
203,
3639,
2583,
12,
203,
5411,
389,
2704,
15647,
480,
10363,
16,
203,
5411,
315,
13691,
30,
2780,
7412,
358,
783,
10363,
6,
203,
3639,
11272,
203,
3639,
10363,
273,
389,
2704,
15647,
31,
203,
3639,
3626,
1000,
15647,
1133,
24899,
2704,
15647,
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
] |
./partial_match/1/0xeFC812A74Ea5dB6913E676F20fef66b22FC66432/sources/RedemptionPoolAlloyx.sol | @notice Pulls assets from the DAO msig @param _amount amount of assets to pull Transfer alloyx from the caller to this contract | function depositAlloy(uint256 _amount) external onlyOwner {
ALLOYX.safeTransferFrom(msg.sender, address(this), _amount);
totalAlloyxDeposited += _amount;
emit AlloyxDeposit(totalAlloyxDeposited);
}
| 3,583,961 | [
1,
9629,
87,
7176,
628,
326,
463,
20463,
4086,
360,
225,
389,
8949,
3844,
434,
7176,
358,
6892,
12279,
524,
2466,
92,
628,
326,
4894,
358,
333,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
1067,
2466,
12,
11890,
5034,
389,
8949,
13,
3903,
1338,
5541,
288,
203,
3639,
7981,
1502,
61,
60,
18,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
1769,
203,
203,
3639,
2078,
1067,
2466,
92,
758,
1724,
329,
1011,
389,
8949,
31,
203,
3639,
3626,
2262,
2466,
92,
758,
1724,
12,
4963,
1067,
2466,
92,
758,
1724,
329,
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
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.